Click on QMenu's action to display QDialog, how to keep QMenu open
-
I have an example as follows: When you click on the Button, a QMenu will be displayed including 2 Actions. When you click on any action, a QDialog will be displayed.
I want when displaying the QDialog, my QMenu remains intact and does not close. After working on the QDialog, closing the QDialog can still continue working on the QMenu.
Is that possible? Can someone help me? This is my code:from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QMenu, QAction, QDialog, QLabel class MyApplication(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("My Application") self.button = QPushButton("Show Menu", self) self.button.clicked.connect(self.show_menu) self.setCentralWidget(self.button) self.menu = None # Track the menu def show_menu(self): if self.menu is None: self.menu = QMenu(self) action1 = QAction("Option 1", self) action2 = QAction("Option 2", self) self.menu.addAction(action1) self.menu.addAction(action2) action1.triggered.connect(lambda: self.show_dialog(1)) action2.triggered.connect(lambda: self.show_dialog(2)) self.menu.exec_(self.button.mapToGlobal(self.button.rect().bottomLeft())) def show_dialog(self, option): dialog = QDialog(self) dialog.setWindowTitle(f"Option {option} Dialog") label = QLabel(f"Option {option} selected!", dialog) dialog.exec_() if __name__ == '__main__': app = QApplication([]) window = MyApplication() window.show() app.exec_()
-
@Hai-Anh-Luu
I don't have an answer as to how or whether you can alter behaviour. ButQMenu.exec_()
(orQMenu.popup()
) shows the menu as a popup, and that means that it will disappear after you click an item (or click outside it). You would have to find a way to change that.13 years ago(!) Prevent a QMenu from closing when one of its QAction is triggered was posted, maybe the suggestions there will work for you? Things change slowly in the Qt world :) Goggle
qmenu keep open
gets another couple of hits, though it does not look like this question is asked frequently.