Hello,

I have a question about the life time of QMenu. I use it as a custom context menu. It is declared on MainWindow class level (this->contextMenu) and is intended to be cleared and reused with different QActions depending on the column that is right-clicked in a QTableView. Here is my code:

Qt Code:
  1. void MainWindow::on_tableView_customContextMenuRequested(const QPoint &pos)
  2. {
  3. this->contextMenu->clear();
  4. //...
  5. //Some code to add QActions depending on the column under pos
  6. //...
  7. //In a first approach the context menu is placed 10px right of the mouse click position
  8. QPoint kPos = ui->tableView->viewport()->mapToGlobal(pos) + QPoint(10, 0);
  9. if (this->contextMenu->isVisible()) {
  10. this->contextMenu->move(kPos);
  11. } else {
  12. this->contextMenu->popup(kPos);
  13. }
  14. }
To copy to clipboard, switch view to plain text mode 

This code sort of works. If I right-click, the context menu opens. If I select a QAction from the menu, the menu is closed and the QAction is executed. However, if I don't select a QAction, but right-click on another cell, I want the context menu to be moved to the new position with a new set of QActions. My approach is to clear the QMenu, build it up from scratch and move it to the new position.
The problem is: Sometimes it works and sometimes it doesn't (I feel it depends on if I move the mouse between button down and button up). If it doesn't work, the menu is hidden instead. If I close the main window in this situation (hidden context menu), the main window won't close. The first close attempt seems to close the invisible context menu, the second attempt finally closes the main window.

  • Is the intended feature maybe to close the QMenu if popup() is called and it is already open?
  • What is the intended life time of a QMenu:
  • If I select a QAction, is it intended to be destroyed? Or hidden?
  • What is the best practice approach to reuse a QMenu?


What am I doing wrong?