0

我想在没有用户交互的情况下在 QWidget 上弹出一个未折叠的 QMenu。目前,右键单击后,我在原本为空的 QWidget 上获得了 QMenu。有没有办法以编程方式调用 contextMenuEvent(QContextMenuEvent *event) 信号?

作为替代方案,我可以向菜单栏添加一个菜单。然而,这是崩溃的。是否可以显示未折叠的菜单?

我很高兴有任何想法。谢谢!

编辑:代码片段

 TestMenu::TestMenu(QWidget *parent)
 : QWidget(parent)
{
   ui.setupUi(this);
  //remove frame from widget
   this->setWindowFlags(Qt::FramelessWindowHint );
  //add menu
  QMenu menu(this);
  QAction* firstEntry = new QAction(tr("Ask a question"), this);
  connect(firstEntry, SIGNAL(triggered()), this, SIGNAL(askCollegueDialogRequested()));
  menu.addAction(firstEntry);
  menu.popup(this->mapToGlobal(QPoint(0,0)));
  menu.activateWindow();
 }

我只看到没有菜单的空小部件。我从另一个类调用小部件的 show()。问题可能是 QMenu 并没有真正添加到小部件中。但我现在不知道如何在不使用菜单栏的情况下添加它:-(。

4

1 回答 1

0

使用QMenu::popup()。例如:

menu->popup( widget->mapToGlobal(QPoint(0,0)) );
menu->activateWindow(); // this is needed if the menu cannot be controlled with keyboard.

更新 1 以响应已编辑的问题: 在您的情况下,您不应该在堆栈上创建 QMenu,它将在构造函数退出之前自动删除。而是在堆上创建它。而且您无法在构造函数中弹出菜单,它只会短暂出现并消失。稍后使用 QTimer::singleShot 显示它。

m_contextMenu = new QMenu(this);

QAction* firstEntry = new QAction(tr("Ask a question"), this);
connect(firstEntry, SIGNAL(triggered()), this, SIGNAL(askCollegueDialogRequested()));
m_contextMenu->addAction(firstEntry);

QTimer::singleShot(0, this, SLOT(showMenu()));

显示菜单:

void TestMenu::showMenu()
{
  m_contextMenu->popup(this->mapToGlobal(QPoint(0, 0)));
  m_contextMenu->activateWindow();    
}
于 2014-08-26T16:34:31.577 回答