A QMenu Popup to Confirm a Button Click
-
I am writing code in QT to replicate this operation in an application previously written for MFC: In a dialog with a list of items, when one selects an item and clicks the "Delete" button, instead of just deleting it, a popup menu with one item, "Confirm Delete" appears and the user must click it to perform the delete. If they click somewhere else or hit ESC, the menu closes and the delete operation does not get executed.
Here is the I thought would work, but the menu never appears and the QAction pointer is left as nullptr, so it just sees the operation cancelled:
void MyDialog::on_Delete_clicked() { QMenu menu( ui->Delete ); QAction *atAction = nullptr; menu.addSection( "Confirm Delete" ); menu.popup( QCursor::pos(), atAction ); qDebug() << "Result:" << ( ( atAction == nullptr ) ? "Escaped" : "Confirmed" ); }
Once I can get this to have a result that confirms the user clicked the menu, the debug line will be removed and a call to the code that deletes the list item will replace it.
-
@Calvin-H-C
I believeQMenu::popUp()
is asynchronous/does not wait. Andmenu
goes out of scope, hence you don't see it. Did you meanmenu.exec()
here? -
@JonB I had tried both to see what would display the menu, and should have lead with using exed() first:
void OccupancyTab::on_Del1_clicked() { QMenu menu( ui->Del1 ); menu.addSection( "Confirm Delete" ); QAction *Result = menu.exec( QCursor::pos() ); qDebug() << "Result:" << ( ( Result == nullptr ) ? "Escaped" : "Confirmed" ); }
As you mention, popup() is asynchronous, so it returned immediately which indicated "Escaped".
Using exec(), it waits, but still does not display the menu. If one hits ESC or clicks somewhere on the screen, it will return and indicate "Escaped".
What am I missing to actually display the menu?
-
@Calvin-H-C Why are you using QMenu::addSection()?
-
@Calvin-H-C
Well per the link that's just a separator with a tooltip. Maybe you don't see it. UseaddAction()
, does it then show?