Qt World Summit: Register Today!

Creating a widget which can hold an image and text

  • I have created a widget which contain an image and a text, also there is a space between the image and the text.

    I am painting the image and text in the paintevent but it is not aligned properly.

    NB: I want the image + " space " + text placed exactly at the middle..

    Please help me in this

       QPainter painter(this);
    QRect paintRect = rect();
    QPixmap pixmap = icon().pixmap(m_frameSize);
    painter.fillRect(rect(), QColor(170, 30, 30));   // filling the widget with background color
    int iconXCoordinate = (paintRect.width()) / 4;
    int iconYCoordinate = (paintRect.height() - pixmap.height()) / 2;
    painter.drawPixmap(iconXCoordinate,iconYCoordinate,pixmap);  //drawing image
    painter.setPen(QColor(255, 255, 255));
    int textXCoordinate = iconXCoordinate + pixmap.width() +2 ; //2 pixel space
    int textYCoordinate = iconYCoordinate;
    QFontMetrics fontMetrics = painter.fontMetrics();
    QRect fontRect = fontMetrics.tightBoundingRect(m_Text);
    painter.drawText((paintRect.width()/2), textYCoordinate + round( ( (double) fontRect.height())), m_Text);

    This is not brining the image and text at the centre of the rectange. can you provide any logic to achieve thus

  • Lifetime Qt Champion


    The coordinate system is not based on the center of what you want to paint.

    Please take a look at the corresponding chapter in Qt's documentation.

Log in to reply