如何以编程方式关闭 QMenu

How to programmatically close QMenu

我的情况很具体。我想将 QAction 放入 QToolbar 并达到以下行为:

  1. 带有图标的可勾选 QAction
  2. 右侧的经典箭头,用于显示菜单
  3. 按此箭头,我的 QDialog 应该会出现在屏幕上,而不是像 QMenu 那样

现在我对一起实施所有这些事情感到有点困惑。

现在我已经创建 QAction 将其添加到工具栏并且还创建了一个空的 QMenu 因为我不知道如何添加另一个 "dropdown" 箭头方法。
因此,我还将我的插槽连接到 QMenu aboutToShow() 信号,现在,我可以在 QMenu 显示之前创建我的对话框并 exec() 它。但这里出现了主要问题:在我用我的对话框完成所有操作后,单击 OK 按钮 QMenu 试图出现,但由于它是空的,它什么也不显示,只有在我左键单击后才能进行进一步的操作"close" 这个菜单的某个地方。

有什么方法可以强制 QMenu 不显示或可以从 QMenu 继承并重新实现它的行为(我试过用 exec() show() QMenupopup() 方法在从它继承后,但是 none 当菜单出现在屏幕上时被调用) ?

这是对我有用的解决方案。

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
    }
}

它在每个平台上都运行良好,并且可以满足我的需求。 希望,这会对某人有所帮助。我花了一周的时间试图找到这个解决方案。