使用QDialog()创建模态对话框
发布时间:2023-12-16 11:07:46
QDialog()是Qt中的一个对话框类,可以用于创建模态对话框。模态对话框是一种对话框,在对话框上操作时,用户不能与其他窗口进行交互,必须先完成对话框的操作才能继续操作其他窗口。
下面是一个使用QDialog()创建模态对话框的例子:
import sys
from PyQt5.QtWidgets import QApplication, QDialog, QLabel, QVBoxLayout, QPushButton
class MyDialog(QDialog):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle('模态对话框')
layout = QVBoxLayout()
label = QLabel('这是一个模态对话框')
layout.addWidget(label)
button = QPushButton('确定')
button.clicked.connect(self.accept)
layout.addWidget(button)
self.setLayout(layout)
if __name__ == '__main__':
app = QApplication(sys.argv)
dialog = MyDialog()
dialog.setModal(True) # 设置对话框为模态对话框
dialog.exec_()
sys.exit(app.exec_())
在上面的例子中,创建了一个名为MyDialog的自定义对话框类,继承自QDialog。在initUI()方法中,设置对话框的标题为"模态对话框",创建一个垂直布局并添加一个标签和一个按钮。
接下来,在主程序中创建了一个QApplication对象和MyDialog对象。然后,调用setModal(True)方法将对话框设置为模态对话框。最后,调用exec_()方法显示对话框,并调用app.exec_()进入Qt的事件循环中。
当用户点击对话框上的"确定"按钮时,对话框将通过调用accept()方法关闭,并返回到主程序中。
总结:使用QDialog()创建模态对话框的过程包括创建一个自定义对话框类,设置对话框的布局和内容,调用setModal(True)将对话框设置为模态对话框,调用exec_()显示对话框,并处理对话框的返回结果。
