[英]How to programmatically close QMenu
我有非常具体的情况。 我想将QAction
放入QToolbar
并达到以下行为:
QAction
。QDialog
应该出现在屏幕上,而不是QMenu
现在我对一起实现所有这些事情有点困惑。
现在我已经创建了QAction
,将它添加到工具栏,还创建了一个空的QMenu
,因为我不知道如何以另一种方式添加“下拉”箭头。
因此,我还将我的插槽连接到QMenu
aboutToShow()
信号,现在,我可以在QMenu
显示之前创建我的对话框并exec()
它。 但这里出现了主要问题:在我用我的对话框完成所有操作后,单击OK
按钮QMenu
试图出现,但由于它是空的,它什么都不显示,并且只有在我左键单击某个位置以“关闭”此菜单后,进一步的操作才可用。
有什么方法可以强制QMenu
不显示或可以从QMenu
继承并重新实现其行为(我尝试在从 QMenu 子类化之后使用QMenu
的exec()
show()
popup()
方法来做到这一点,但没有一个当菜单出现在屏幕上时被调用)?
这是解决方案,对我有用。
class QCustomMenu : public QMenu
{
Q_OBJECT
public:
QCustomMenu(QObject *parent = 0):QMenu(parent){};
};
在代码中:
QAction* myActionWithMenu = new QAction ( "ActionText", toolbar);
QCustomMenu* myMenu = new QCustomMenu(toolbar);
connect(myMenu, SIGNAL(aboutToShow()), this, SLOT(execMyMenu()));
execMyMenu()
实现:
void execMyMenu(){
m_activeMenu = (QCustomMenu*)sender(); // m_activeMenu -- private member of your head class, needs to point to active custom menu
QMyDialog* dlg = new QMyDialog();
// setup your dialog with needed information
dlg->exec();
// handle return information
m_myTimer = startTimer(10); // m_myTimer -- private member of your head(MainWindow or smth like that) class
}
现在我们必须处理 timerEvent 并关闭我们的菜单:
void MyHeadClass::timerEvent(QTimerEvent *event)
{
// Check if it is our "empty"-menu timer
if ( event->timerId()==m_myTimer )
{
m_activeMenu->close(); // closing empty menu
killTimer(m_myTimer); // deactivating timer
m_myTimer = 0; // seting timer identifier to zero
m_activeMenu = NULL; // as well as active menu pointer to NULL
}
}
它在每个平台上都运行良好,并且可以满足我的需求。 希望,这会对某人有所帮助。 我花了一周的时间试图找到这个解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.