|
| 1 | +import sys |
| 2 | + |
| 3 | +from PySide6 import QtWidgets |
| 4 | + |
| 5 | +""" |
| 6 | +QDialog 信号 |
| 7 | +
|
| 8 | +accepted() 用户接受对话框或调用accept()、done(QDialog.Accepted)时发射此信号 |
| 9 | +rejected() 用户拒绝对话框或调用reject()、done(QDialog.Rejected)时发射此信号 |
| 10 | +finished(result: int) 当通过用户操作、done()、accept()、reject()设置了对话框的结果码时发射此信号,结果码作为参数传递 |
| 11 | +
|
| 12 | +""" |
| 13 | + |
| 14 | + |
| 15 | +class MyWidget(QtWidgets.QWidget): |
| 16 | + def __init__(self, *args, **kwargs): |
| 17 | + super().__init__(*args, **kwargs) |
| 18 | + self.setWindowTitle("QDialog 信号") |
| 19 | + self.resize(800, 600) |
| 20 | + self.dialog = QtWidgets.QDialog(self) |
| 21 | + self.setup_dialog() |
| 22 | + self.setup_ui() |
| 23 | + |
| 24 | + def setup_dialog(self) -> None: |
| 25 | + """设置对话框窗口""" |
| 26 | + self.dialog.setWindowTitle("对话框-测试信号") |
| 27 | + |
| 28 | + accept_btn = QtWidgets.QPushButton("Accept") |
| 29 | + accept_btn.clicked.connect(self.dialog.accept) # type: ignore |
| 30 | + |
| 31 | + reject_btn = QtWidgets.QPushButton("Reject") |
| 32 | + reject_btn.clicked.connect(self.dialog.reject) # type: ignore |
| 33 | + |
| 34 | + done_btn = QtWidgets.QPushButton("Done") |
| 35 | + |
| 36 | + done_btn.clicked.connect(lambda: self.dialog.done(QtWidgets.QDialog.Accepted)) # type: ignore |
| 37 | + # done_btn.clicked.connect(lambda: self.dialog.done(QtWidgets.QDialog.Rejected)) # type: ignore |
| 38 | + |
| 39 | + # 布局管理器 |
| 40 | + layout = QtWidgets.QHBoxLayout() |
| 41 | + layout.addWidget(accept_btn) |
| 42 | + layout.addWidget(reject_btn) |
| 43 | + layout.addWidget(done_btn) |
| 44 | + self.dialog.setLayout(layout) |
| 45 | + |
| 46 | + def setup_ui(self) -> None: |
| 47 | + """设置界面""" |
| 48 | + |
| 49 | + # 用于显示对话框 |
| 50 | + open_dialog_btn = QtWidgets.QPushButton("打开对话框(Open)", self) |
| 51 | + open_dialog_btn.move(200, 200) |
| 52 | + open_dialog_btn.clicked.connect(self.dialog.open) # type: ignore |
| 53 | + |
| 54 | + # 用于显示对话框返回值 |
| 55 | + info_label_1 = QtWidgets.QLabel(self) |
| 56 | + info_label_1.move(220, 300) |
| 57 | + info_label_1.resize(200, 50) |
| 58 | + |
| 59 | + info_label_2 = QtWidgets.QLabel(self) |
| 60 | + info_label_2.move(220, 360) |
| 61 | + info_label_2.resize(200, 50) |
| 62 | + |
| 63 | + self.dialog.accepted.connect(lambda: info_label_1.setText("对话框窗口被接受了")) # type: ignore |
| 64 | + self.dialog.rejected.connect(lambda: info_label_1.setText("对话框窗口被拒绝了")) # type: ignore |
| 65 | + self.dialog.finished.connect(lambda result: info_label_2.setText(f"对话框窗口的返回值为:{result}")) # type: ignore |
| 66 | + |
| 67 | + |
| 68 | +if __name__ == "__main__": |
| 69 | + app = QtWidgets.QApplication(sys.argv) |
| 70 | + window = MyWidget() |
| 71 | + window.show() |
| 72 | + sys.exit(app.exec()) |
0 commit comments