简体   繁体   English

在 PyQt 的模式对话框中使用下拉按钮

[英]Use a drop-down button inside a modal dialog in PyQt

I want to create a modal dialog in PyQt, which contains a drop-down button.我想在 PyQt 中创建一个模式对话框,其中包含一个下拉按钮。 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) ,然后问题就解决了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM