Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 290
Noel Avatar asked Nov 27 '14 00:11

Noel


2 Answers

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

See the related Qt suggestion.

like image 70
CharlesB Avatar answered Nov 03 '22 12:11

CharlesB


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");
like image 34
Nejat Avatar answered Nov 03 '22 11:11

Nejat