Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Draw an object horizontally and with a vertical offset on QPainter



  • Hi,
    I want create a image composed of three elements : one image and two text. To do this, I use QPainter. I can draw elements but I can't succeed to correctly align them. I want each element align horizontally and placed below each other.

     ___________________
    |      _______      |
    |     | image |     |
    |     |_______|     |
    |                   |
    |     my text 1     |
    |     my text 2     |
    |___________________|
    

    For the moment, I placed them approximately.

    QImage image(152, 152, QImage::Format_ARGB32_Premultiplied);
    
    QPainter painter(&image);
    painter.fillRect(image.rect(), Qt::white);
    QImage pictureSensor("image.png");
    int posX = (image.width()-pictureSensor.width())/2;
    painter.drawImage(posX,10, pictureSensor);
    
    painter.drawText(30,110, "my text 1");
    
    painter.drawText(20,140, "my text2);
    
    image.save("output.png");
    

    I can horizontally placed text but in this case I can't set 'y' position :

        painter.drawText(image.rect(), Qt::AlignHCenter, QString("text"));
    

    Is there any solution ?


  • Lifetime Qt Champion

    @helenebro said:

    painter.drawText(image.rect(), Qt::AlignHCenter, QString("text"));

    Hi the image.rect() defines the rect where is aligns.
    So if you offset the rect.y (in a copy QRect)
    u can move start of area.

    Alternatively, you can use
    http://doc.qt.io/qt-5/qfontmetrics.html
    To get width() of you text and do the centering your self.


Log in to reply