I want to create a modal dialog in PyQt, which contains a drop-down button. Here is what I've tried:
from PyQt5.QtWidgets import QDialog, QVBoxLayout, QPushButton, QMenu, QApplication, QMainWindow, QLabel, QWidget
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("MainWindow")
btn = QPushButton("Open FileDialog")
btn.clicked.connect(self.openFileDialog)
vbox = QVBoxLayout()
vbox.addWidget(btn)
self.setLayout(vbox)
def openFileDialog(self):
file_dialog = FileDialog(self)
file_dialog.exec()
class FileDialog(QDialog):
def __init__(self, parent: QWidget):
super().__init__(parent)
menu = QMenu()
menu.addAction("Open")
menu.addAction("Save")
btn = QPushButton("More")
btn.setMenu(menu)
vbox = QVBoxLayout()
vbox.addWidget(btn)
self.setLayout(vbox)
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
The drop-down button doesn't work, I can click on it, it shows two options, but I can neither select nor click on any of them.
Is there any way to solve the problem?
感谢@musicamante 和@ekhumoro 的评论,我将menu = QMenu()
更改为menu = QMenu(self)
,然后问题就解决了。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.