欢迎访问宙启技术站
智能推送

PySide2.QtWidgets中的模态对话框

发布时间:2023-12-25 17:47:58

PySide2.QtWidgets是Qt的Python绑定库,提供了许多用于创建图形用户界面的类和函数。其中包括了模态对话框(Modal Dialog)的支持,可以通过一些简单的步骤创建自己的模态对话框并显示在界面上。

下面是一个使用PySide2.QtWidgets创建模态对话框的示例:

import sys
from PySide2.QtWidgets import QApplication, QDialog, QVBoxLayout, QLabel, QPushButton

# 自定义的模态对话框类
class MyDialog(QDialog):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("My Dialog")
        self.layout = QVBoxLayout()

        # 在对话框上添加控件
        self.label = QLabel("This is a modal dialog.")
        self.layout.addWidget(self.label)

        self.close_button = QPushButton("Close")
        self.close_button.clicked.connect(self.close_dialog)
        self.layout.addWidget(self.close_button)

        self.setLayout(self.layout)

    def close_dialog(self):
        self.accept()

# 创建主窗口类
class MainWindow(QDialog):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Main Window")
        self.layout = QVBoxLayout()

        self.label = QLabel("This is the main window.")
        self.layout.addWidget(self.label)

        self.button = QPushButton("Open Dialog")
        self.button.clicked.connect(self.open_dialog)
        self.layout.addWidget(self.button)

        self.setLayout(self.layout)

    def open_dialog(self):
        # 创建并显示模态对话框
        dialog = MyDialog()
        result = dialog.exec_()

        if result == QDialog.Accepted:
            self.label.setText("Dialog was accepted.")
        else:
            self.label.setText("Dialog was rejected.")

if __name__ == "__main__":
    app = QApplication(sys.argv)

    window = MainWindow()
    window.show()

    sys.exit(app.exec_())

上述代码中,首先创建了一个自定义的模态对话框类MyDialog,它继承自QDialog。该对话框包含一个QLabel和一个QPushButton,用于展示一些信息并关闭对话框。

接下来,创建了一个主窗口类MainWindow,它继承自QDialog。该窗口包含一个QLabel和一个QPushButton,用于触发打开模态对话框的事件。

open_dialog函数中,创建并显示了模态对话框MyDialog。使用exec_()函数来显示对话框,并返回对话框的结果。如果对话框被接受(按下了关闭按钮),则更新主窗口上的QLabel的文本为"Dialog was accepted.",否则更新为"Dialog was rejected."。

最后,在主程序中创建了一个应用程序对象,并显示主窗口。调用app.exec_()来进入应用程序的主循环中,直到应用程序退出。