0

I want to pop up a not collapsed QMenu on a QWidget without user interaction. At the moment, I get the QMenu on the otherwise empty QWidget after a right click. Is there any way to invoke a contextMenuEvent(QContextMenuEvent *event) signal programmatically?

As an alternative I could add a menu to the menubar. However, this is collapsed. Would it be possible to show the menu not collapsed?

I am glad for any idea. Thanks!

Edit: Code snippet

 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();
 }

I only see the empty widget without the menu. I call the show() for the widget from another class. The problem might be that the QMenu is not really added to the widget. But I don't now how to add it without using a menubar :-(.

Natalie
  • 445
  • 2
  • 5
  • 18

1 Answers1

0

Use QMenu::popup(). Eg:

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

Update 1 in response to the edited question: You should not create QMenu on stack in your case, it will be deleted automatically before the constructor exits. Create it on heap instead. And you cannot popup the menu in your constructor, it will only appear briefly and disappear. Use QTimer::singleShot to show it later.

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()));

showMenu:

void TestMenu::showMenu()
{
  m_contextMenu->popup(this->mapToGlobal(QPoint(0, 0)));
  m_contextMenu->activateWindow();    
}
fxam
  • 3,874
  • 1
  • 22
  • 32
  • Thanks a lot! I added some code including your suggestion. I can't see the QMenu. Anything I am missing? – Natalie Aug 26 '14 at 17:05