A tooltip is a small box with a short explanation that appears when the mouse rests on a widget. It saves you from putting a sentence next to a button and it does not take up any room.
Every PyQt widget has a setToolTip() method. The text can be plain, or a little html if you want it bold or on more than one line.
Setting up Tooltips in PyQt5
Note: Remember, tooltips aren’t visible on mobile devices since they lack a mouse cursor.
The setToolTip method is essential for defining a tooltip in PyQt. Once a widget is created, this method can be employed to assign a tooltip to it.
pybutton.setToolTip('This is a tooltip for the QPushButton widget') |
To view the tooltip, hover the mouse over the widget and wait momentarily.
You can put html in a tooltip, so <b> and <br> work.
button.setToolTip('This is a <b>QPushButton</b> widget') |
If you’re looking to tweak the tooltip’s font style, PyQt’s got you covered:
QToolTip.setFont(QFont('SansSerif', 10)) |
Practical Tooltip Example with PyQt5
The example below puts a tooltip on a button. Move the mouse over the button and the text appears.
import sys |
Setting one
button.setToolTip('Save the file')is the short version.- The text can be a few lines, use
\n. - You can use a bit of html, so
<b>and<br>work. setToolTipDuration(3000)sets how long it stays, in milliseconds.setToolTipsVisible(False)turns them off for a whole window.
Write the tooltip for someone who has never seen your app. "OK" is not a tooltip, "Save the file to disk" is. Keep it to one line, a long tooltip is a label you should have put in the window instead.
Tooltips only show up with a mouse. If your app is used on a touch screen, put the text somewhere visible instead.
Reading helps, writing fixes it. PyChallenge has exercises on this and you can try them right now.
