How to make context menu to work only on a specific widget?
Solved
General and Desktop
-
Hi there,
I am making a simple file manager for educational purposes. And it is interesting to know how can I make context menu to appear only when the user right clicks on QListView widget? Here is the picture for better visualization:
Image
As you can see the menu appears even when I right click on menuBar (or on statusBar, or on toolBar)I am adding action items to the context menu like this
void MainWindow::contextMenuEvent(QContextMenuEvent *event) { QMenu menu(this); menu.addAction(ui->actionOpen); menu.addAction(ui->actionNew_Directory); menu.addSeparator(); menu.addAction(ui->actionCompress); menu.addAction(ui->actionDecompress); menu.addSeparator(); menu.addAction(ui->actionRemove_Object); menu.exec(event->globalPos()); }
Thanks :)
-
@Aram said:
void MainWindow::contextMenuEvent(...
That's the problem. You want the context menu on list view but you're handling it on the main window. Subclass the QListView and handle the event there:
void YourQListViewSubclass::contextMenuEvent(QContextMenuEvent *event) { ...
-
@Chris-Kawa thanks for your answer!
-
you don't have to subclass the ListView. You can add Actions on the widgets.
See addAction(QAction *action)