在PYQT中的模态对话框中使用下拉按钮

发布于 2025-01-28 05:00:56 字数 1339 浏览 2 评论 0原文

我想在PYQT中创建一个模态对话框,其中包含一个下拉按钮。这是我尝试过的:

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_())

下拉按钮不起作用,我可以单击它,它显示两个选项,但是我既不能选择也不能单击任何一个。

有什么办法可以解决问题?

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.

enter image description here

Is there any way to solve the problem?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

笨笨の傻瓜 2025-02-04 05:00:56

多亏了@musicamante和@ekhumoro的评论,我将菜单= qmenu()更改为菜单= qmenu(self),然后解决了问题。

Thanks to the comments by @musicamante and @ekhumoro, I changed menu = QMenu() to menu = QMenu(self), then the problem got solved.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文