Search code examples
c++qttooltipqmenuqaction

QTooltip for QActions in QMenu


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?


Solution

  • 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");