8

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.

buhtz
  • 10,774
  • 18
  • 76
  • 149

2 Answers2

17

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.

Antonio Dias
  • 2,751
  • 20
  • 40
9

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)