PDA

View Full Version : How to embed text to pixmap in QLabel?



sciton
6th December 2017, 18:36
Hello,

How to embed text to pixmap in QLabel?
Suppose I have the following code inherited from a QLabel class:
void myLabel::setImage(QImage myImage, QString myText)
{
QPixmap pixmap = QPixmap::fromImage(myImage);
setPixmap();
// once this statements are done myImage is shown properly
// now if I do for the text:
setText(myText); // I don't see myText at all.
}

I've tried using QPainter but still did not show the text embedded in the QLabel.
Help please!

Tom

d_stranz
6th December 2017, 20:52
QPixmap pixmap = QPixmap::fromImage(myImage);
setPixmap();

I'd like to know how you manage to set a pixmap with this code. :confused:

From the QLabel docs:


Setting the pixmap clears any previous content.

and


Setting the text clears any previous content.

You get one or the other, but not both. And according to the "code" you posted, you should be seeing the text and not the pixmap.

sciton
6th December 2017, 23:04
Thank you, and I just solve it.




QPainter p(&myImage);
p.save();
// set the text style here
p.drawText(..., myText); // place it wherever with the alignment flag
p.restore();

//then:
void myLabel::setImage(QImage myImage, QString myText)
{
QPixmap pixmap = QPixmap::fromImage(myImage);
setPixmap();
...
}

In other word, I did what someone suggested. put the text on top of the image at first, before the image is mapped into the pixmap.

d_stranz
8th December 2017, 14:29
Yes, that's about the only way to do it with a standard QLabel. The QPainter save() and restore() operations are meaningless, since your QPainter variable is created on the stack, is deleted after it is used to paint the image, and has no relationship to any QPainter instance used anywhere else in your code.

Your code should also be "style aware" so that the text is painted using the style that the rest of your app uses. Maybe you are doing that. "..." hides a lot of relevant details.