我希望能够显示QMenu项目的工具提示(QActions).我所取得的最好成绩是将QAction的悬停信号连接到QTooltip节目:
connect(action,&QAction::hovered,[=]{ QToolTip::showText(QCursor::pos(),text,this); });
解决方法
您可以继承QMenu并重新实现QMenu :: event()以拦截QEvent :: ToolTip事件并调用QToolTip :: showText来设置活动操作的工具提示:
#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); } };
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");