QTooltip for QActions in QMenu

2019-04-06 16:02发布

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条回答
淡お忘
2楼-- · 2019-04-06 16:30

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");
查看更多
ら.Afraid
3楼-- · 2019-04-06 16:30

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

See the related Qt suggestion.

查看更多
登录 后发表回答