Tool Tips Example#
The Tool Tips example shows how to provide static and dynamic tool tips for an application’s widgets.
The simplest and most common way to set a widget’s tool tip is by calling its
setToolTip() function (static tool tips). Then the tool tip is shown whenever the cursor points at the widget. We show how to do this with our application’s tool buttons. But it is also possible to show different tool tips depending on the cursor’s position (dynamic tooltips). This approach uses mouse tracking and event handling to determine what widgets are located under the cursor at any point in time, and displays their tool tips. The tool tips for the shape items in our application are implemented using the latter approach.
Tooltips application the user can create new shape items with the provided tool buttons, and move the items around using the mouse. Tooltips are provided whenever the cursor is pointing to a shape item or one of the buttons.
The Tooltips example consists of two classes:
ShapeItemis a custom widget representing one single shape item.
QWidgetand is the application’s main widget.
First we will review the
SortingBox class, then we will take a look at the
SortingBox Class Definition#
class SortingBox(QWidget): Q_OBJECT # public SortingBox(QWidget parent = None) # protected event = bool(QEvent event) def resizeEvent(event): def paintEvent(event): def mousePressEvent(event): def mouseMoveEvent(event): def mouseReleaseEvent(event): # private slots def createNewCircle(): def createNewSquare(): def createNewTriangle():
SortingBox class inherits
QWidget , and it is the Tooltips application’s main widget. We reimplement several of the event handlers.
event() function provides tooltips, the
resize() function makes sure the application appears consistently when the user resizes the main widget, and the
paintEvent() function displays the shape items within the
SortingBox widget. The mouse event handlers are reimplemented to make the user able to move the items around.
In addition we need three private slots to make the user able to create new shape items.
# private updateButtonGeometry = int(QToolButton button, int x, int y) def createShapeItem(path, toolTip,): pos, = QPoint() itemAt = int(QPoint pos) def moveItemTo(pos): initialItemPosition = QPoint(QPainterPath path) randomItemPosition = QPoint() initialItemColor = QColor() randomItemColor = QColor() createToolButton(QString = QToolButton()
We also create several private functions: We use the
createToolButton() functions when we are constructing the widget, and we use the
updateButtonGeometry() function whenever the user is resizing the application’s main widget.
itemAt() function determines if there is a shape item at a particular position, and the
moveItemTo() function moves an item to a new position. We use the
randomItemColor() functions to create new shape items.
shapeItems = QList() circlePath = QPainterPath() squarePath = QPainterPath() trianglePath = QPainterPath() previousPosition = QPoint() itemInMotion = ShapeItem() newCircleButton = QToolButton() newSquareButton = QToolButton() newTriangleButton = QToolButton()
We keep all the shape items in a
QList , and we keep three
QPainterPath objects holding the shapes of a circle, a square and a triangle. We also need to have a pointer to an item when it is moving, and we need to know its previous position.
SortingBox Class Implementation#
def __init__(self, parent): super().__init__(parent)
In the constructor, we first set the
WA_StaticContents attribute on the widget. This attribute indicates that the widget contents are north-west aligned and static. On resize, such a widget will receive paint events only for the newly visible part of itself.
To be able to show the appropriate tooltips while the user is moving the cursor around, we need to enable mouse tracking for the widget.
If mouse tracking is disabled (the default), the widget only receives mouse move events when at least one mouse button is pressed while the mouse is being moved. If mouse tracking is enabled, the widget receives mouse move events even if no buttons are pressed.
A widget’s background role defines the brush from the widget’s palette that is used to render the background, and
Base is typically white.
newCircleButton = createToolButton(tr("New Circle"), QIcon(":/images/circle.png"), SLOT(createNewCircle())) newSquareButton = createToolButton(tr("New Square"), QIcon(":/images/square.png"), SLOT(createNewSquare())) newTriangleButton = createToolButton(tr("New Triangle"), QIcon(":/images/triangle.png"), SLOT(createNewTriangle())) circlePath.addEllipse(QRect(0, 0, 100, 100)) squarePath.addRect(QRect(0, 0, 100, 100)) x = trianglePath.currentPosition().x() y = trianglePath.currentPosition().y() trianglePath.moveTo(x + 120 / 2, y) trianglePath.lineTo(0, 100) trianglePath.lineTo(120, 100) trianglePath.lineTo(x + 120 / 2, y)
After creating the application’s tool buttons using the private
createToolButton() function, we construct the shapes of a circle, a square and a triangle using
QPainterPath class provides a container for painting operations, enabling graphical shapes to be constructed and reused. The main advantage of painter paths over normal drawing operations is that complex shapes only need to be created once, but they can be drawn many times using only calls to
Then we set the window title, resize the widget to a suitable size, and finally create three initial shape items using the private
def event(self, QEvent event):
event() is the main event handler and receives all the widget’s events. Normally, we recommend reimplementing one of the specialized event handlers instead of this function. But here we want to catch the
ToolTip events, and since these are rather rare, there exists no specific event handler. For that reason we reimplement the main event handler, and the first thing we need to do is to determine the event’s type:
If the type is
ToolTip , we cast the event to a
QHelpEvent , otherwise we propagate the event using the
QHelpEvent class provides an event that is used to request helpful information about a particular point in a widget.
For example, the
pos() function returns the event’s position relative to the widget to which the event is dispatched. Here we use this information to determine if the position of the event is contained within the area of any of the shape items. If it is, we display the shape item’s tooltip at the position of the event. If not, we hide the tooltip and explicitly ignore the event. This makes sure that the calling code does not start any tooltip specific modes as a result of the event. Note that the
showText() function needs the event’s position in global coordinates provided by
def resizeEvent(self, */): margin = style().pixelMetric(QStyle.PM_LayoutTopMargin) x = width() - margin y = height() - margin y = updateButtonGeometry(newCircleButton, x, y) y = updateButtonGeometry(newSquareButton, x, y) updateButtonGeometry(newTriangleButton, x, y)
resizeEvent() function is reimplemented to receive the resize events dispatched to the widget. It makes sure that the tool buttons keep their position relative to the main widget when the widget is resized. We want the buttons to always be vertically aligned in the application’s bottom right corner, so each time the main widget is resized we update the buttons geometry.
def paintEvent(self, */): painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) for shapeItem in qAsConst(shapeItems):
paintEvent() function is reimplemented to receive paint events for the widget. We create a
QPainter for the
SortingBox widget, and run through the list of created shape items, drawing each item at its defined position.
The painter will by default draw all the shape items at position (0,0) in the
SortingBox widget. The
translate() function translates the coordinate system by the given offset, making each shape item appear at its defined position. But remember to translate the coordinate system back when the item is drawn, otherwise the next shape item will appear at a position relative to the item drawn last.
setBrush() function sets the current brush used by the painter. When the provided argument is a
QColor , the function calls the appropriate
QBrush constructor which creates a brush with the specified color and
SolidPattern style. The
drawPath() function draws the given path using the current pen for outline and the current brush for filling.
def mousePressEvent(self, event): if event.button() == Qt.LeftButton: index = itemAt(event.position().toPoint()) if index != -1: itemInMotion = shapeItems[index] previousPosition = event.position().toPoint() shapeItems.move(index, shapeItems.size() - 1) update()
mousePressEvent() function is reimplemented to receive the mouse press events dispatched to the widget. It determines if an event’s position is contained within the area of any of the shape items, using the private
If an item covers the position, we store a pointer to that item and the event’s position. If several of the shape items cover the position, we store the pointer to the uppermost item. Finally, we move the shape item to the end of the list, and make a call to the
update() function to make the item appear on top.
update() function does not cause an immediate repaint; instead it schedules a paint event for processing when Qt returns to the main event loop.
def mouseMoveEvent(self, event): if (event.buttons() Qt.LeftButton) and itemInMotion: moveItemTo(event.position().toPoint())
mouseMoveEvent() function is reimplemented to receive mouse move events for the widget. If the left mouse button is pressed and there exists a shape item in motion, we use the private
moveItemTo() function to move the item with an offset corresponding to the offset between the positions of the current mouse event and the previous one.
def mouseReleaseEvent(self, event): if event.button() == Qt.LeftButton and itemInMotion: moveItemTo(event.position().toPoint()) itemInMotion = None
mouseReleaseEvent() function is reimplemented to receive the mouse release events dispatched to the widget. If the left mouse button is pressed and there exists a shape item in motion, we use the private
moveItemTo() function to move the item like we did in
mouseMoveEvent(). But then we remove the pointer to the item in motion, making the shape item’s position final for now. To move the item further, the user will need to press the left mouse button again.
def createNewCircle(self): count = 1 createShapeItem(circlePath, tr("Circle <%1>").arg(++count), randomItemPosition(), randomItemColor()) def createNewSquare(self): count = 1 createShapeItem(squarePath, tr("Square <%1>").arg(++count), randomItemPosition(), randomItemColor()) def createNewTriangle(self): count = 1 createShapeItem(trianglePath, tr("Triangle <%1>").arg(++count), randomItemPosition(), randomItemColor())
createNewTriangle() slots simply create new shape items, using the private
def itemAt(self, QPoint pos): for i in range(-1, shapeItems.size() - 1, -1): ShapeItem item = shapeItems[i] if item.path().contains(pos - item.position()): return i return -1
itemAt() function, we run through the list of created shape items to check if the given position is contained within the area of any of the shape items.
For each shape item we use the
contains() function to find out if the item’s painter path contains the position. If it does we return the index of the item, otherwise we return -1. We run through the list backwards to get the index of the uppermost shape item in case several items cover the position.
def moveItemTo(self, pos): offset = pos - previousPosition itemInMotion.setPosition(itemInMotion.position() + offset)
moveItemTo() function moves the shape item in motion, and the parameter
pos is the position of a mouse event. First we calculate the offset between the parameter
pos and the previous mouse event position. Then we add the offset to the current position of the item in motion.
It is tempting to simply set the position of the item to be the parameter
pos. But an item’s position defines the top left corner of the item’s bounding rectangle, and the parameter
pos can be any point; The suggested shortcut would cause the item to jump to a position where the cursor is pointing to the bounding rectangle’s top left corner, regardless of the item’s previous position.
Finally, we update the previous mouse event position, and make a call to the
update() function to make the item appear at its new position.
def updateButtonGeometry(self, QToolButton button, int x, int y): size = button.sizeHint() button.setGeometry(x - size.rwidth(), y - size.rheight(), size.rwidth(), size.rheight()) return y - size.rheight() - style().pixelMetric(QStyle.PM_LayoutVerticalSpacing)
updateButtonGeometry() function we set the geometry for the given button. The parameter coordinates define the bottom right corner of the button. We use these coordinates and the button’s size hint to determine the position of the upper left corner. This position, and the button’s width and height, are the arguments required by the
In the end, we calculate and return the y-coordinate of the bottom right corner of the next button. We use the
style() function to retrieve the widget’s GUI style, and then
pixelMetric() to determine the widget’s preferred default spacing between its child widgets.
def createShapeItem(self, path,): toolTip, = QString() color) = QColor() shapeItem = ShapeItem() shapeItem.setPath(path) shapeItem.setToolTip(toolTip) shapeItem.setPosition(pos) shapeItem.setColor(color) shapeItems.append(shapeItem) update()
createShapeItem() function creates a single shape item. It sets the path, tooltip, position and color, using the item’s own functions. In the end, the function appends the new item to the list of shape items, and calls the
update() function to make it appear with the other items within the
SortingBox::createToolButton(QString = QToolButton() icon, = QIcon() button = QToolButton(self) button.setToolTip(toolTip) button.setIcon(icon) button.setIconSize(QSize(32, 32)) connect(button, SIGNAL(clicked()), self, member) return button
createToolButton() function is called from the
SortingBox constructor. We create a tool button with the given tooltip and icon. The button’s parent is the
SortingBox widget, and its size is 32 x 32 pixels. Before we return the button, we connect it to the given slot.
def initialItemPosition(self, QPainterPath path): x = int() y = (height() - qRound(path.controlPointRect().height()) / 2) if shapeItems.size() == 0: x = ((3 * width()) / 2 - qRound(path.controlPointRect().width())) / 2 else: x = (width() / shapeItems.size() - qRound(path.controlPointRect().width())) / 2 return QPoint(x, y)
initialItemPosition() function is also called from the constructor. We want the three first items to initially be centered in the middle of the
SortingBox widget, and we use this function to calculate their positions.
def randomItemPosition(self): return QPoint(QRandomGenerator.global().bounded(width() - 120), QRandomGenerator.global().bounded(height() - 120))
Whenever the user creates a new shape item, we want the new item to appear at a random position, and we use the
randomItemPosition() function to calculate such a position. We make sure that the item appears within the visible area of the
SortingBox widget, using the widget’s current width and height when calculating the random coordinates.
def initialItemColor(self): return QColor.fromHsv(((shapeItems.size() + 1) * 85) % 256, 255, 190)
initialItemColor() function is called from the constructor. The purposes of both functions are purely cosmetic: We want to control the initial position and color of the three first items.
def randomItemColor(self): return QColor.fromHsv(QRandomGenerator.global().bounded(256), 255, 190)
randomItemColor() function is implemented to give the shape items the user creates, a random color.
ShapeItem Class Definition#
class ShapeItem(): # public def setPath(path): def setToolTip(toolTip): def setPosition(position): def setColor(color): path = QPainterPath() position = QPoint() color = QColor() toolTip = QString() # private myPath = QPainterPath() myPosition = QPoint() myColor = QColor() myToolTip = QString()
ShapeItem class is a custom widget representing one single shape item. The widget has a path, a position, a color and a tooltip. We need functions to set or modify these objects, as well as functions that return them. We make the latter functions
const to prohibit any modifications of the objects, i.e. prohibiting unauthorized manipulation of the shape items appearance.
ShapeItem Class Implementation#
def path(self): return myPath def position(self): return myPosition def color(self): return myColor def toolTip(self): return myToolTip
This first group of functions simply return the objects that are requested. The objects are returned as constants, i.e. they cannot be modified.
def setPath(self, path): myPath = path def setToolTip(self, toolTip): myToolTip = toolTip def setPosition(self, position): myPosition = position def setColor(self, color): myColor = color
The last group of functions set or modify the shape item’s path, position, color and tooltip, respectively.