QTooltip for QActions in QMenu

半世苍凉 提交于 2019-12-13 11:57:30

问题


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?


回答1:


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



回答2:


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

See the related Qt suggestion.



来源:https://stackoverflow.com/questions/27161122/qtooltip-for-qactions-in-qmenu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!