QMessageBox Widget#

keywords: QMessageBox, MessageBox, Message Box

QMessage 是一个消息弹窗, 用于显示一些消息, 通知, 警告等. 本质上是一个 Dialog.

Examples#

QMessageBox_example_1.py
 1# -*- coding: utf-8 -*-
 2
 3"""
 4这个例子展示了一个简单的 QMessageBox 的用法. 重点是展示了 exec, open, show 三种不同的方法来显示 QMessageBox.
 5"""
 6
 7import sys
 8from PySide6 import QtCore, QtWidgets
 9
10
11class MainWidget(QtWidgets.QWidget):
12    def __init__(self, parent):
13        super().__init__(parent)
14        # fmt: off
15        self.button_wgt_1 = QtWidgets.QPushButton("Button 1", parent=self)
16        self.button_wgt_1.clicked.connect(self.button_1_clicked_handler)
17        self.button_wgt_2 = QtWidgets.QPushButton("Button 2", parent=self)
18        self.button_wgt_2.clicked.connect(self.button_2_clicked_handler)
19        self.button_wgt_3 = QtWidgets.QPushButton("Button 3", parent=self)
20        self.button_wgt_3.clicked.connect(self.button_3_clicked_handler)
21
22        # ref: https://doc.qt.io/qtforpython-6/PySide6/QtWidgets/QMessageBox.html
23        self.msg_box_1 = QtWidgets.QMessageBox(parent=self)
24        self.msg_box_1.setText("This is message box 1")
25        self.msg_box_2 = QtWidgets.QMessageBox(parent=self)
26        self.msg_box_2.setText("This is message box 2")
27        self.msg_box_3 = QtWidgets.QMessageBox(parent=self)
28        self.msg_box_3.setText("This is message box 3")
29        # fmt: on
30
31        self.main_lay = QtWidgets.QHBoxLayout()
32        self.main_lay.addWidget(self.button_wgt_1)
33        self.main_lay.addWidget(self.button_wgt_2)
34        self.main_lay.addWidget(self.button_wgt_3)
35        self.setLayout(self.main_lay)
36
37    @QtCore.Slot()
38    def button_1_clicked_handler(self):
39        """
40        exec() 方法会阻塞程序, 你不点 OK 是不会运行 print("msg box 1 exec() finished") 的.
41        这是 QDialog 的方法. 所有的 QDialog 都有这个方法. 我们比较推荐使用这个方法.
42
43        该方法默认会阻止用户和其他窗口互动.
44        """
45        print("trigger button_1_clicked_handler")
46        # ref: https://doc.qt.io/qtforpython-6/PySide6/QtWidgets/QDialog.html#PySide6.QtWidgets.PySide6.QtWidgets.QDialog.exec
47        self.msg_box_1.exec()
48        print("msg box 1 exec() finished")
49
50    @QtCore.Slot()
51    def button_2_clicked_handler(self):
52        """
53        open() 不会阻塞程序. 你会看到你点击 OK 之前 print("msg box 2 open() finished") 就
54        已经被执行了. 其他方面和 exec() 完全一致.
55
56        该方法默认会阻止用户和其他窗口互动.
57        """
58        print("trigger button_2_clicked_handler")
59        # ref: https://doc.qt.io/qtforpython-6/PySide6/QtWidgets/QMessageBox.html#PySide6.QtWidgets.PySide6.QtWidgets.QMessageBox.open
60        self.msg_box_2.open()
61        print("msg box 2 open() finished")
62
63    @QtCore.Slot()
64    def button_3_clicked_handler(self):
65        """
66        show() 不会阻塞程序. 你会看到你点击 OK 之前 print("msg box 2 open() finished") 就
67        已经被执行了. show 本质上只是显示 widget, 只不过我们的 widget 恰巧是一个 QMessageBox.
68        show 方法不会触发 MessageBox 的一些例如 finished(), buttonClicked() 的信号.
69        它只适用于点击 OK 关闭窗口 (我知道了) 的情况.
70
71        该方法默认会阻止用户和其他窗口互动.
72        """
73        print("trigger button_3_clicked_handler")
74        # ref: https://doc.qt.io/qtforpython-6/PySide6/QtWidgets/QWidget.html#PySide6.QtWidgets.PySide6.QtWidgets.QWidget.show
75        self.msg_box_3.show()
76        print("msg box 3 show() finished")
77
78
79class MainWindow(QtWidgets.QMainWindow):
80    def __init__(self):
81        super().__init__()
82        self.main_wgt = MainWidget(self)
83        self.setCentralWidget(self.main_wgt)
84        self.setGeometry(
85            int(screen_width * 0.25),  # x, at 25% of screen width
86            int(screen_height * 0.25),  # y, at 25% of screen height
87            int(screen_width * 0.5),  # w, 50% screen width
88            int(screen_height * 0.5),  # h, 50% screen height
89        )
90        self.setWindowTitle("QMessageBox Example")
91        self.show()
92
93
94if __name__ == "__main__":
95    app = QtWidgets.QApplication(sys.argv)
96    screen_width, screen_height = app.screens()[0].size().toTuple()
97    main = MainWindow()
98    sys.exit(app.exec())
QMessageBox_example_2.py
 1# -*- coding: utf-8 -*-
 2
 3"""
 4这个例子展示了如何自动关闭 QMessageBox.
 5"""
 6
 7import sys
 8from PySide6 import QtCore, QtWidgets
 9
10
11class MainWidget(QtWidgets.QWidget):
12    def __init__(self, parent):
13        super().__init__(parent)
14        # fmt: off
15        self.button_wgt = QtWidgets.QPushButton("Click Me", parent=self)
16        self.button_wgt.clicked.connect(self.button_clicked_handler)
17        # ref: https://doc.qt.io/qtforpython-6/PySide6/QtWidgets/QMessageBox.html
18        self.msg_box = QtWidgets.QMessageBox(parent=self)
19        self.msg_box.setText("This is a message box, will close in 3 seconds")
20        # fmt: on
21
22        self.main_lay = QtWidgets.QVBoxLayout()
23        self.main_lay.addWidget(self.button_wgt)
24        self.setLayout(self.main_lay)
25
26    @QtCore.Slot()
27    def button_clicked_handler(self):
28        """
29        注意, 这个 timer 可一定不要放在 __init__ 中. 因为 QtCore.QTimer() 一初始化,
30        就开始计时了. 你放在 __init__ 就会导致这个 gui 第一次显示后 3 秒就自动关闭 message box.
31        这时候用户可能还没有点击 button, 还没有打开呢, 你之后再点击 button 的时候, 自然也不会自动关闭了.
32        """
33        print("trigger button_clicked_handler")
34        timer = QtCore.QTimer()
35        timer.setSingleShot(True)
36        timer.timeout.connect(self.msg_box.close)
37        timer.start(3000)  # 1000 milliseconds = 1 second
38        self.msg_box.exec()
39
40
41class MainWindow(QtWidgets.QMainWindow):
42    def __init__(self):
43        super().__init__()
44        self.main_wgt = MainWidget(self)
45        self.setCentralWidget(self.main_wgt)
46        self.setGeometry(
47            int(screen_width * 0.25),  # x, at 25% of screen width
48            int(screen_height * 0.25),  # y, at 25% of screen height
49            int(screen_width * 0.5),  # w, 50% screen width
50            int(screen_height * 0.5),  # h, 50% screen height
51        )
52        self.setWindowTitle("QMessageBox Example")
53        self.show()
54
55
56if __name__ == "__main__":
57    app = QtWidgets.QApplication(sys.argv)
58    screen_width, screen_height = app.screens()[0].size().toTuple()
59    main = MainWindow()
60    sys.exit(app.exec())
QMessageBox_example_3.py
 1# -*- coding: utf-8 -*-
 2
 3"""
 4这个例子展示了如何让 QMessageBox 里出现几个 button 选项, 点击不同的选项就会有不同的效果.
 5"""
 6
 7import sys
 8from PySide6 import QtCore, QtWidgets
 9
10
11class MainWidget(QtWidgets.QWidget):
12    def __init__(self, parent):
13        super().__init__(parent)
14        # fmt: off
15        self.button_wgt = QtWidgets.QPushButton("Click Me", parent=self)
16        self.button_wgt.clicked.connect(self.button_clicked_handler)
17        # ref: https://doc.qt.io/qtforpython-6/PySide6/QtWidgets/QMessageBox.html
18        self.msg_box = QtWidgets.QMessageBox(parent=self)
19        self.msg_box.setText("This is a message box")
20        self.msg_box.setStandardButtons(
21            QtWidgets.QMessageBox.StandardButton.Save
22            | QtWidgets.QMessageBox.StandardButton.Discard
23            | QtWidgets.QMessageBox.StandardButton.Cancel
24        )
25        # fmt: on
26
27        self.main_lay = QtWidgets.QVBoxLayout()
28        self.main_lay.addWidget(self.button_wgt)
29        self.setLayout(self.main_lay)
30
31    @QtCore.Slot()
32    def button_clicked_handler(self):
33        """
34        如果你要根据用户在 Message box 里点击的按钮来做不同的事情, 你需要用 ``exec`` 方法来
35        阻塞程序, 并获得反馈后才继续执行.
36
37        ``QtWidgets.QMessageBox.StandardButton`` 是一个 enum, 里面有很多预先定义好的
38        button, 非常实用.
39        """
40        print("trigger button_clicked_handler")
41        received = self.msg_box.exec()
42        if received == QtWidgets.QMessageBox.StandardButton.Save:
43            print("user clicked Save")
44        elif received == QtWidgets.QMessageBox.StandardButton.Discard:
45            print("user clicked Discard")
46        elif received == QtWidgets.QMessageBox.StandardButton.Cancel:
47            print("user clicked Cancel")
48        else:  # pragma: no cover
49            raise NotImplementedError
50
51
52class MainWindow(QtWidgets.QMainWindow):
53    def __init__(self):
54        super().__init__()
55        self.main_wgt = MainWidget(self)
56        self.setCentralWidget(self.main_wgt)
57        self.setGeometry(
58            int(screen_width * 0.25),  # x, at 25% of screen width
59            int(screen_height * 0.25),  # y, at 25% of screen height
60            int(screen_width * 0.5),  # w, 50% screen width
61            int(screen_height * 0.5),  # h, 50% screen height
62        )
63        self.setWindowTitle("QMessageBox Example")
64        self.show()
65
66
67if __name__ == "__main__":
68    app = QtWidgets.QApplication(sys.argv)
69    screen_width, screen_height = app.screens()[0].size().toTuple()
70    main = MainWindow()
71    sys.exit(app.exec())

Reference#