📜  PyQt-QMessageBox

📅  最后修改于: 2020-11-08 08:10:50             🧑  作者: Mango


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

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

Sr.No. Methods & Description
1

setIcon()

Displays predefined icon corresponding to severity of the message

Question Question

Information Information

Warning Warning

Critical Critical

2

setText()

Sets the text of the main message to be displayed

3

setInformativeText()

Displays additional information

4

setDetailText()

Dialog shows a Details button. This text appears on clicking it

5

setTitle()

Displays the custom title of dialog

6

setStandardButtons()

List of standard buttons to be displayed. Each button is associated with

QMessageBox.Ok 0x00000400

QMessageBox.Open 0x00002000

QMessageBox.Save 0x00000800

QMessageBox.Cancel 0x00400000

QMessageBox.Close 0x00200000

QMessageBox.Yes 0x00004000

QMessageBox.No 0x00010000

QMessageBox.Abort 0x00040000

QMessageBox.Retry 0x00080000

QMessageBox.Ignore 0x00100000

7

setDefaultButton()

Sets the button as default. It emits the clicked signal if Enter is pressed

8

setEscapeButton()

Sets the button to be treated as clicked if the escape key is pressed

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

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()信号连接到slot函数,该函数标识信号源的标题。

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输出1QMessageBox输出2