QTooltip for QActions in QMenu

I want to show tooltips for QMenu elements ( QAction s). The best I have achieved is to connect a hanging QAction signal to a QTooltip showing:

 connect(action, &QAction::hovered, [=]{ QToolTip::showText(QCursor::pos(), text, this); }); 

The problem is that sometimes the program will position the tooltip under the menu, especially when changing the menu.

Is there a way to make the tooltip show on top?

+6
source share
2 answers

You can subclass QMenu and override QMenu::event() to catch the QEvent::ToolTip event and call QToolTip::showText to set a tooltip for the active action:

 #include <QtGui> class Menu : public QMenu { Q_OBJECT public: Menu(){} bool event (QEvent * e) { const QHelpEvent *helpEvent = static_cast <QHelpEvent *>(e); if (helpEvent->type() == QEvent::ToolTip && activeAction() != 0) { QToolTip::showText(helpEvent->globalPos(), activeAction()->toolTip()); } else { QToolTip::hideText(); } return QMenu::event(e); } }; 

Now you can use your menu:

 Menu *menu = new Menu(); menu->setTitle("Test menu"); menuBar()->addMenu(menu); QAction *action1 = menu->addAction("First"); action1->setToolTip("First action"); QAction *action2 = menu->addAction("Second"); action2->setToolTip("Second action"); 
+5
source

Since Qt 5.1, you can use the QMenu toolTipsVisible property, which is set to false by default.

See the related Qt sentence .

+6
source

Source: https://habr.com/ru/post/978769/


All Articles