Important: Please read the Qt Code of Conduct -

Setting non-expanding text on an expanding Image

  • I have a Qimage on Qlabel which expands based on the window expansion. Hence the Image also expands.
    I have set simple text into the QImage using Qpainter as below

    QPainter* painter = new QPainter(&myImage);
    painter->setFont(QFont("Arial", 5));
    painter->drawText(myImage.rect(), Qt::AlignLeft, "MyText");

    But i don't want the text on the image to expand . How can I acheive it ?
    Also the image is going to be grayscale. Hence, the text also changes to grayscale. I want the text to be colorful (Eg : Red, white etc.).

    Any suggestions.

  • Lifetime Qt Champion

    I would make my own QLabel and then simply first paint the image, then paint the text.
    So the text is not part of the image but painted dynamically. ( that also allows for colors etc)
    Currently, you make the text part of the image so it scales with it and is kinda hrd to remove again.

  • @mrjj @SGaist
    This code below is the paintevent override

    void ClickableDistanceLabel::paintEvent(QPaintEvent *event)
    qInfo () << FUNCTION;

    QPainter p(this);
    p.drawImage(this->rect(), pixmap()->toImage());
    QLabel *distanceLabel = new QLabel(this);
    distanceLabel->setFrameStyle(QFrame::Panel | QFrame::Raised);
    distanceLabel->setAlignment(Qt::AlignTop | Qt::AlignLeft);


    But i don't get the text "Distance" on it.
    Am I missing something.


  • Lifetime Qt Champion

    That will generate a billion QLabels !
    since each paintEvent will allocate a new.
    and besides its wrong to do allocate it in the paintEvent, that
    you should do elsewhere if you really must use a QLabel.

    Why not just draw the text since you have a painter?

    p.drawText( 20,20, "Distance");
    It can also take aligement options etc.

  • @mrjj

    The below code works. I need not create a label everytime.

    QPainter painter(this);
    painter.drawImage(this->rect(), pixmap()->toImage());
    painter.setFont(QFont("Arial", 13));
    painter.drawText(QRectF(0,0,90,20), "Distance");


  • Lifetime Qt Champion


    If you want you could do
    painter.drawPixmap(this->rect(), pixmap());
    so you dont have to convert to QImage every time you draw.

Log in to reply