Pyqt5系列(六)-基本界面组件之MessageBox

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhulove86/article/details/52524735

消息框针对某个场景以文本的形式向用户进行提示,为了获取用户的响应消息框可以显示图标和标准按钮。在实际的界面交互中,经常会看到各种类型的消息框,显示关于消息框,显示严重错误消息框,显示警告消息框等等。由于这些对话框在各个程序中都是一样的,所以QT中就统一提供了一个QMessageBox的类,这样在所有程序中都可以直接使用。

QMessageBox提供两套接口来实现,一种是static functions(静态方法调用),另外一种 the property-base API(基于属性的API)。直接调用静态方法是一种比较简单的途径,但是没有基于属性API的方式灵活。在QT的官网上推荐使用the property-base API。

Static functions 方式:

QMessageBox用于显示消息提示。一般会使用到其提供的几个 static 函数(C++层的函数原型,其参数类型和python中的一样):

返回值 函数原型
void about(QWidget *parent, const QString &title, const QString &text) 显示关于对话框。这是一个最简单的对话框,对话框只有一个 OK 按钮
void aboutQt(QWidget *parent, const QString &title = QString()) 显示关于 Qt 对话框。该对话框用于显示有关 Qt 的信息。
StandardButton critical(QWidget *parent, const QString &title, const QString &text, StandardButtons buttons = Ok, StandardButtondefaultButton = NoButton) 显示严重错误对话框。这个对话框将显示一个红色的错误符号。我们可以通过 buttons 参数指明其显示的按钮。默认情况下只有一个 Ok 按钮,我们可以使用StandardButtons类型指定多种按钮
StandardButton information(QWidget *parent, const QString &title, const QString &text, StandardButtons buttons = Ok, StandardButton defaultButton = NoButton) 显示提示对话框,提供一个普通信息图标
StandardButton question(QWidget *parent, const QString &title, const QString &text, StandardButtons buttons = StandardButtons( Yes No ), StandardButton defaultButton = NoButton) 显示询问对话框,提供一个问号图标
StandardButton warning(QWidget *parent, const QString &title, const QString &text, StandardButtons buttons = Ok, StandardButton defaultButton = NoButton) 显示警告对话框,提供一个黄色叹号图标图标

通过一个示例来进行说明各个方法的使用:

#-*- coding:utf-8 -*-
'''
MessageBox
'''
__author__ = 'Tony Zhu'

from PyQt5.QtWidgets import QApplication, QWidget, QLineEdit, QMessageBox, QGridLayout, QLabel, QPushButton, QFrame

class MessageBox(QWidget):
    def __init__(self):       
        super(MessageBox,self).__init__()
        self.initUi()

    def initUi(self):
        self.setWindowTitle("MessageBox")
        self.setGeometry(400,400,300,290)


        self.questionLabel = QLabel("Question:")
        self.questionLabel.setFrameStyle(QFrame.Panel|QFrame.Sunken)
        self.infoLabel = QLabel("Information:")
        self.infoLabel.setFrameStyle(QFrame.Panel|QFrame.Sunken)
        self.warningLabel = QLabel("Warning:")
        self.warningLabel.setFrameStyle(QFrame.Panel|QFrame.Sunken)
        self.criticalLabel = QLabel("Critical:")
        self.criticalLabel.setFrameStyle(QFrame.Panel|QFrame.Sunken)
        self.aboutLabel = QLabel("About:")
        self.aboutLabel.setFrameStyle(QFrame.Panel|QFrame.Sunken)
        self.aboutQtLabel = QLabel("About QT:")
        self.aboutQtLabel.setFrameStyle(QFrame.Panel|QFrame.Sunken)
        self.resultLabel = QLabel("Result:")
        self.resultLabel.setFrameStyle(QFrame.Panel|QFrame.Sunken)

        questButton=QPushButton("...")
        questButton.clicked.connect(self.selectQuestion)
        infoButton=QPushButton("...")
        infoButton.clicked.connect(self.selectInfo)
        warningButton=QPushButton("...")
        warningButton.clicked.connect(self.selectWarning)
        criticalButton=QPushButton("...")
        criticalButton.clicked.connect(self.selectCritical)
        aboutButton=QPushButton("...")
        aboutButton.clicked.connect(self.selectAbout)
        aboutQtButton=QPushButton("...")
        aboutQtButton.clicked.connect(self.selectAboutQt)

        mainLayout=QGridLayout()
        mainLayout.addWidget(self.questionLabel,0,0)
        mainLayout.addWidget(questButton,0,1)    
        mainLayout.addWidget(self.infoLabel,1,0)
        mainLayout.addWidget(infoButton,1,1)
        mainLayout.addWidget(self.warningLabel,2,0)
        mainLayout.addWidget(warningButton,2,1)
        mainLayout.addWidget(self.criticalLabel,3,0)
        mainLayout.addWidget(criticalButton,3,1)
        mainLayout.addWidget(self.aboutLabel,4,0)
        mainLayout.addWidget(aboutButton,4,1)
        mainLayout.addWidget(self.aboutQtLabel,5,0)
        mainLayout.addWidget(aboutQtButton,5,1)
        mainLayout.addWidget(self.resultLabel,6,1)

        self.setLayout(mainLayout)



    def selectQuestion(self):
        button = QMessageBox.question(self,"Question","检测到程序有更新,是否安装最新版本?",
                                      QMessageBox.Ok|QMessageBox.Cancel,QMessageBox.Ok)

        if button == QMessageBox.Ok:
            self.resultLabel.setText("<h2>Question:<font color=red>  OK</font></h2>")
        elif button == QMessageBox.Cancel:
            self.resultLabel.setText("<h2>Question:<font color=red>  Cancel</font></h2>")
        else:
            return

    def selectInfo(self):
        QMessageBox.information(self,"Information","程序当前版本为V3.11")
        self.resultLabel.setText("Information")
        4
    def selectWarning(self):
        button = QMessageBox.warning(self,"Warning","恢复出厂设置将导致用户数据丢失,是否继续操作?",
                                      QMessageBox.Reset|QMessageBox.Help|QMessageBox.Cancel,QMessageBox.Reset)

        if button == QMessageBox.Reset:
            self.resultLabel.setText("<h2>Warning:<font color=red>  Reset</font></h2>")
        elif button == QMessageBox.Help:
            self.resultLabel.setText("<h2>Warning:<font color=red>  Help</font></h2>")
        elif button == QMessageBox.Cancel:
            self.resultLabel.setText("<h2>Warning:<font color=red>  Cancel</font></h2>")
        else:
            return

    def selectCritical(self):
        QMessageBox.critical(self,"Critical","服务器宕机!")
        self.resultLabel.setText("<h2><font color=red>Critical</font></h2>")

    def selectAbout(self):
        QMessageBox.about(self,"About","Copyright 2015 Tony zhu.\n All Right reserved.")
        self.resultLabel.setText("About")

    def selectAboutQt(self):
        QMessageBox.aboutQt(self,"About Qt")
        self.resultLabel.setText("About Qt")

if __name__=="__main__":
    import sys
    app=QApplication(sys.argv)
    myshow=MessageBox()
    myshow.show()
    sys.exit(app.exec_())

运行之后的结果:
这里写图片描述

示例说明:
通过点击不同的按钮,来选择不同类型的消息框,并将处理的结果显示在resultLabel中。
代码分析:
L19~32:

self.questionLabel = QLabel("Question:")        self.questionLabel.setFrameStyle(QFrame.Panel|QFrame.Sunken)

   .......

self.resultLabel = QLabel("Result:")     self.resultLabel.setFrameStyle(QFrame.Panel|QFrame.Sunken)

定义不同消息类型的标签,其中resultLabel显示不同message box执行的结果。

L34~45:

        questButton=QPushButton("...")
        questButton.clicked.connect(self.selectQuestion)

        .....

        aboutQtButton=QPushButton("...")
        aboutQtButton.clicked.connect(self.selectAboutQt)

定义针对不同类型操作的按钮,并且将对应按钮的clicked信号和自定义的槽函数绑定在一起。

L47~60:

        mainLayout=QGridLayout()
        mainLayout.addWidget(self.questionLabel,0,0)
        mainLayout.addWidget(questButton,0,1)    

        .......

        mainLayout.addWidget(self.aboutQtLabel,5,0)
        mainLayout.addWidget(aboutQtButton,5,1)
        mainLayout.addWidget(self.resultLabel,6,1)

实例化网格布局,并将定义的标签和按钮添加到布局的对应位置。

1、question 类型
question类型的执行代码段如下:

    def selectQuestion(self):
        button = QMessageBox.question(self,"Question","检测到程序有更新,是否安装最新版本?",
                                      QMessageBox.Ok|QMessageBox.Cancel,QMessageBox.Ok)

        if button == QMessageBox.Ok:
            self.resultLabel.setText("<h2>Question:<font color=red>  OK</font></h2>")
        elif button == QMessageBox.Cancel:
            self.resultLabel.setText("<h2>Question:<font color=red>  Cancel</font></h2>")
        else:
            return

调用static方法question()生产question类型的消息框(Ok和cancel按钮,默认选择Ok按钮),该执行之后返回用户选择的按钮。通过判断返回的按钮类型,在resultLabel中显示对应的内容。

question(QWidget *parent, const QString &title, const QString &text, StandardButtons buttons = StandardButtons( Yes | No ), StandardButton defaultButton = NoButton)

第1个参数parent,用于指定父组件;

第2个参数title,是消息框中的标题;

第3个参数text,消息框中显示的内容。

第4个参数buttons ,消息框中显示的button,它的取值是 StandardButtons ,每个选项可以使用 | 运算组合起来。如QMessageBox.Ok|QMessageBox.Cancel,

第5个参数button ,消息框中默认选中的button。

这个函数有一个返回值,用于确定用户点击的是哪一个按钮。我们可以直接获取其返回值。如果返回值是 Ok,也就是说用户点击了 Ok按钮,

QLabel支持HTML形式的文本显示,在resultLabel中是通过HTML的语法形式进行显示的。具体可以参考一下HTML语法。

执行的结果:
question
question OK

2、information类型
information类型的执行代码段如下:

    def selectInfo(self):
        QMessageBox.information(self,"Information","程序当前版本为V3.11")
        self.resultLabel.setText("Information")

调用static方法information()生产information类型的消息框,该类型默认有一个Ok按钮。

information(QWidget *parent, const QString &title, const QString &text, StandardButtons buttons = Ok, StandardButton defaultButton = NoButton)

第1,2,3参数,同question类型的说明。

第4个参数buttons ,默认参数,默认为Ok按钮。

执行的结果:
information

3、warning类型
warning类型的执行代码段如下:

    def selectWarning(self):
        button = QMessageBox.warning(self,"Warning","恢复出厂设置将导致用户数据丢失,是否继续操作?",
                                      QMessageBox.Reset|QMessageBox.Help|QMessageBox.Cancel,QMessageBox.Reset)

        if button == QMessageBox.Reset:
            self.resultLabel.setText("<h2>Warning:<font color=red>  Reset</font></h2>")
        elif button == QMessageBox.Help:
            self.resultLabel.setText("<h2>Warning:<font color=red>  Help</font></h2>")
        elif button == QMessageBox.Cancel:
            self.resultLabel.setText("<h2>Warning:<font color=red>  Cancel</font></h2>")
        else:
            return

调用static方法warning()生产warning类型的消息框(Reset、Help和Cancel按钮,默认选择Reset按钮),该执行之后返回用户选择的按钮。通过判断返回的按钮类型,在resultLabel中显示对应的内容。

warning(QWidget *parent, const QString &title, const QString &text, StandardButtons buttons = Ok, StandardButton defaultButton = NoButton)

参数同question类型。

执行的结果:
warning

4、critical类型
critical类型的执行代码段如下:

    def selectCritical(self):
        QMessageBox.critical(self,"Critical","服务器宕机!")
        self.resultLabel.setText("<h2><font color=red>Critical</font></h2>")

调用static方法critical()生产critical类型的消息框。

critical(QWidget *parent, const QString &title, const QString &text, StandardButtons buttons = Ok, StandardButtondefaultButton = NoButton)

参数说明同information类型。

执行的结果:
critical

5、about类型
about类型的执行代码段如下:

    def selectAbout(self):
        QMessageBox.about(self,"About","Copyright 2015 Tony zhu.\n All Right reserved.")
        self.resultLabel.setText("About")

调用static方法about()生产about类型的消息框。

about(QWidget *parent, const QString &title, const QString &text)

第1个参数parent,用于指定父组件;

第2个参数title,是消息框中的标题;

第3个参数text,消息框中显示的内容。

执行的结果:
about

6、aboutQt 类型
aboutQt 类型的执行代码段如下:

    def selectAboutQt(self):
        QMessageBox.aboutQt(self,"About Qt")
        self.resultLabel.setText("About Qt")

调用static方法aboutQt()生产aboutQt类型的消息框。

aboutQt(QWidget *parent, const QString &title = QString())

第1个参数parent,用于指定父组件;

第2个参数title,是消息框中的标题;

其中提示内容来自QT的about中的信息。

执行的结果:
about qt



The property-base API 方式:

通过上述的例子可以看出直接调用QMessageBox的static方法可以很方便的生成各种类型的消息框,但是这种方式是一种既定的显示风格。
QMessageBox类的 static 函数优点是方便使用,缺点也很明显:非常不灵活。我们只能使用简单的几种形式。为了能够定制QMessageBox细节,我们必须使用QMessageBox的属性设置 API。
实例说明:

#-*- coding:utf-8 -*-
'''
MessageBox
'''
__author__ = 'Tony Zhu'

from PyQt5.QtWidgets import QApplication, QWidget, QLineEdit, QMessageBox, QHBoxLayout, QLabel, QPushButton, QFrame

class MessageBox(QWidget):
    def __init__(self):       
        super(MessageBox,self).__init__()
        self.initUi()

    def initUi(self):
        self.setWindowTitle("MessageBox")
        self.setGeometry(400,400,300,290)

        mainLayout = QHBoxLayout()
        self.displayLabel = QLabel("  ")
        self.displayLabel.setFrameStyle(QFrame.Panel|QFrame.Sunken)
        mainLayout.addWidget(self.displayLabel)
        self.setLayout(mainLayout)

        msgBox = QMessageBox()
        msgBox.setIcon(QMessageBox.Information)
        msgBox.setWindowTitle("The property-base API")
        msgBox.setText("The Python file  has been modified.");
        msgBox.setInformativeText("Do you want to save your changes?");
        msgBox.setDetailedText("Python is powerful... and fast; \nplays well with others;\n \
runs everywhere; \n is friendly & easy to learn; \nis Open.")
        msgBox.setStandardButtons(QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel);
        msgBox.setDefaultButton(QMessageBox.Save);

        ret = msgBox.exec()
        if ret == QMessageBox.Save:
            self.displayLabel.setText("Save")
        elif ret == QMessageBox.Discard:
            self.displayLabel.setText("Discard")
        elif ret == QMessageBox.Cancel:
            self.displayLabel.setText("Cancel")
        else:
            pass


if __name__=="__main__":
    import sys
    app=QApplication(sys.argv)
    myshow=MessageBox()
    myshow.show()
    sys.exit(app.exec_())

执行的结果:
Property-base

示例说明:
程序启动的时候直接显示自定义的messagebox,并且在resultLabel中显示选择的结果。
代码分析:
L26:
msgBox.setWindowTitle(“The property-base API”)
通过setWindowTitle()设定消息框的标题。

L27:
msgBox.setText(“The Python file has been modified.”);
通过setText()设定消息框的提示信息。

L28:
msgBox.setInformativeText(“Do you want to save your changes?”)
setInformativeText(),在对话框中显示的简单说明文字

L29:
msgBox.setDetailedText(“Python is powerful… and fast; \nplays well with others;\n \
runs everywhere; \n is friendly & easy to learn; \nis Open.”)

setDetailedText(),设定消息框中的详细文本信息。当设定详细文本的时候,对话框自动增加“Show Details”按钮。
这里写图片描述

通过上述的例子,可以发现通过the property-base API的方式,可以更灵活的定义messagebox。

QMessageBox 常用属性:

StandardButtons:

Constant Value Description
QMessageBox.Ok 0x00000400 An “OK” button defined with the AcceptRole.
QMessageBox.Open 0x00002000 An “Open” button defined with the AcceptRole.
QMessageBox.Save 0x00000800 A “Save” button defined with the AcceptRole.
QMessageBox.Cancel 0x00400000 A “Cancel” button defined with the RejectRole.
QMessageBox.Close 0x00200000 A “Close” button defined with the RejectRole.
QMessageBox.Discard 0x00800000 A “Discard” or “Don’t Save” button, depending on the platform, defined with the DestructiveRole.
QMessageBox.Apply 0x02000000 An “Apply” button defined with the ApplyRole.
QMessageBox.Reset 0x04000000 A “Reset” button defined with the ResetRole.
QMessageBox.RestoreDefaults 0x08000000 A “Restore Defaults” button defined with the ResetRole.
QMessageBox.Help 0x01000000 A “Help” button defined with the HelpRole.
QMessageBox.SaveAll 0x00001000 A “Save All” button defined with the AcceptRole.
QMessageBox.Yes 0x00004000 A “Yes” button defined with the YesRole.
QMessageBox.YesToAll 0x00008000 A “Yes to All” button defined with the YesRole.
QMessageBox.No 0x00010000 A “No” button defined with the NoRole.
QMessageBox.NoToAll 0x00020000 A “No to All” button defined with the NoRole.
QMessageBox.Abort 0x00040000 An “Abort” button defined with the RejectRole.
QMessageBox.Retry 0x00080000 A “Retry” button defined with the AcceptRole.
QMessageBox.Ignore 0x00100000 An “Ignore” button defined with the AcceptRole.
QMessageBox.NoButton 0x00000000 An invalid button.

* QMessageBox.Icon:*

Constant Value Description
QMessageBox.NoIcon 0 the message box does not have any icon.
QMessageBox.Question 4 an icon indicating that the message is asking a question.
QMessageBox.Information 1 an icon indicating that the message is nothing out of the ordinary.
QMessageBox.Warning 2 an icon indicating that the message is a warning, but can be dealt with.
QMessageBox.Critical 3 an icon indicating that the message represents a critical problem.

猜你喜欢

转载自blog.csdn.net/zhulove86/article/details/52524735