QMenu中用于QAction的QTooltip [英] QTooltip for QActions in QMenu
问题描述
我希望能够显示QMenu
个项目(QAction
s)的工具提示.我取得的最好成绩是将QAction
的悬停信号连接到QTooltip
节目:
I want to be able to show ToolTips for QMenu
items (QAction
s). 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?
推荐答案
您可以将QMenu
子类化并重新实现QMenu::event()
来拦截QEvent::ToolTip
事件,并调用QToolTip::showText
设置活动操作的工具提示:
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");
这篇关于QMenu中用于QAction的QTooltip的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!