QTooltip for QActions in QMenu

6.6k views Asked by At

I want to be able to show ToolTips for QMenu items (QActions). The best I have achieved is to connect the hovered signal of the QAction to a QTooltip show:

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

The problem is that sometimes the program will position the tooltip below the menu, specially when changing menus.

Is there any way to force the tooltip to show on top?

2

There are 2 answers

0
Nejat On BEST ANSWER

You can subclass QMenu and reimplementing QMenu::event() to intercept the QEvent::ToolTip event and call QToolTip::showText to set the 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 custom menu like :

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");
0
CharlesB On

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

See the related Qt suggestion.