PyQt5 QMessageBox


QMessageBox 是一种常用的模态对话框,用于显示一些信息性消息,并可选择要求用户通过单击其上的任何一个标准按钮来做出响应。每个标准按钮都有一个预定义的标题、一个角色并返回一个预定义的十六进制数字。

下表给出了与 QMessageBox 类相关的重要方法和枚举:

序号. 方法和描述
1

设置图标()

显示与消息严重性相对应的预定义图标

  • Question
  • 信息
  • Warning
  • Critical
2

设置文本()

设置要显示的主要消息的文本

3

设置信息文本()

显示附加信息

4

setDetailText()

对话框显示一个详细信息按钮。此文本在单击时出现

5

设置标题()

显示对话框的自定义标题

6

设置标准按钮()

要显示的标准按钮列表。每个按钮都与

QMessageBox.Ok 0x00000400

QMessageBox.Open 0x00002000

QMessageBox.Save 0x00000800

QMessageBox.Cancel 0x00400000

QMessageBox.Close 0x00200000

QMessageBox.是 0x00004000

QMessageBox.No 0x00010000

QMessageBox.Abort 0x00040000

QMessageBox.Retry 0x00080000

QMessageBox.Ignore 0x00100000

7

设置默认按钮()

将按钮设置为默认值。如果按下 Enter,它会发出 clicked 信号

8

setEscapeButton()

设置按钮在按下退出键时被视为单击

例子


在下面的例子中,点击顶层窗口按钮的信号,连接的函数显示消息框对话框。

msg = QMessageBox()
msg.setIcon(QMessageBox.Information)
msg.setText("This is a message box")
msg.setInformativeText("This is additional information")
msg.setWindowTitle("MessageBox demo")
msg.setDetailedText("The details are as follows:")

setStandardButton() 函数显示所需的按钮。

msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)

buttonClicked() 信号连接到一个槽函数,该函数标识信号源的标题。

msg.buttonClicked.connect(msgbtn)

示例完整代码如下:

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

def window():
    app = QApplication(sys.argv)
    w = QWidget()
    b = QPushButton(w)
    b.setText("Show message!")
   
    b.move(100,50)
    b.clicked.connect(showdialog)
    w.setWindowTitle("PyQt MessageBox demo")
    w.show()
    sys.exit(app.exec_())

def showdialog():
    msg = QMessageBox()
    msg.setIcon(QMessageBox.Information)
   
    msg.setText("This is a message box")
    msg.setInformativeText("This is additional information")
    msg.setWindowTitle("MessageBox demo")
    msg.setDetailedText("The details are as follows:")
    msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
    msg.buttonClicked.connect(msgbtn)

    retval = msg.exec_()

def msgbtn(i):
    print ("Button pressed is:",i.text())

if __name__ == '__main__':
    window()

上面的代码产生以下输出。单击主窗口按钮时弹出消息框:

QMessageBox 输出

如果点击 MessageBox 上的 Ok 或 Cancel 按钮,控制台会产生以下输出:

Button pressed is: OK
Button pressed is: Cancel