Pyqt 简明教程

PyQt - QMessageBox

QMessageBox 是一个常用的模态对话框,用于显示一些信息消息,还可以让用户通过点击其上的任意一个标准按钮进行响应。每个标准按钮都有一个预定义的标题、一个角色,并返回一个预定义的十六进制数。

与 QMessageBox 类相关的重要方法和枚举在下表中给出−

Sr.No.

Methods & Description

1

setIcon() 显示与消息的严重性相对应的预定义图标,例如 Question Information Warning Critical

2

setText() 设置要显示的主消息的文本

3

setInformativeText() Displays additional information

4

setDetailText() 对话框显示一个“详细信息”按钮。这个文本会在此按钮被点击时出现

5

setTitle() 显示对话框的自定义标题

6

setStandardButtons() 要显示的标准按钮列表。每个按钮都与以下相关联QMessageBox.Ok 0x00000400QMessageBox.Open 0x00002000QMessageBox.Save 0x00000800QMessageBox.Cancel 0x00400000QMessageBox.Close 0x00200000QMessageBox.Yes 0x00004000QMessageBox.No 0x00010000QMessageBox.Abort 0x00040000QMessageBox.Retry 0x00080000QMessageBox.Ignore 0x00100000

7

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

8

setEscapeButton() 将按钮设置为在按下 Escape 键时视为已单击

Example

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

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 PyQt4.QtGui import *
from PyQt4.QtCore import *

def window():
   app = QApplication(sys.argv)
   w = QWidget()
   b = QPushButton(w)
   b.setText("Show message!")

   b.move(50,50)
   b.clicked.connect(showdialog)
   w.setWindowTitle("PyQt Dialog 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_()
   print "value of pressed message box button:", retval

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

if __name__ == '__main__':
   window()

上述代码生成以下输出 -

qmessagebox output1
qmessagebox output2