Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a picture or image in a QToolTip

Tags:

qt

Is there a way to show a picture/image in a QToolTip?

I want to show small images of keyboard-buttons to explain the user which buttons/shortcuts he can use on that specific widget.

like image 604
buhtz Avatar asked Dec 15 '15 17:12

buhtz


2 Answers

You can easily show images with the following html code:

QToolTip::showText(QCursor::pos(), "<img src=':/icon.png'>Message", this, QRect(), 5000);

This example will show a tooltip with the image from Qt resources and the text for 5 seconds.

For more details, you can see this video: https://youtu.be/X9JD8gKGZ00

Edit1:

If you want to show an image from memory, you can save the QImage/QPixmap to memory (preferably using some lossless compression like PNG) and convert it to base 64 and load it with the html code, like this:

QImage icon = QImage(10, 10, QImage::Format_ARGB32);
icon.fill(QColor(255, 0, 0, 100));
QByteArray data;
QBuffer buffer(&data);
icon.save(&buffer, "PNG", 100);
QString html = QString("<img src='data:image/png;base64, %0'>Message").arg(QString(data.toBase64()));
QToolTip::showText(QCursor::pos(), html, this, QRect(), 5000);

Edit2: Corrected the html string as @Damon Lynch suggests.

like image 180
Antonio Dias Avatar answered Oct 18 '22 07:10

Antonio Dias


With respect to the HTML string, the Python 3 / PyQt equivalent of user2014561's excellent solution to displaying in memory images is like this, assuming a QPixmap (a QImage will work the same):

buffer = QBuffer()
buffer.open(QIODevice.WriteOnly)
pixmap.save(buffer, "PNG", quality=100)
image = bytes(buffer.data().toBase64()).decode()
html = '<img src="data:image/png;base64,{}">'.format(image)
like image 9
Damon Lynch Avatar answered Oct 18 '22 06:10

Damon Lynch