[Introduction to PyQt] The basic PyQt5 controls use: message pop-up, user input, file dialog boxes

Posted by Wolf_22 on Tue, 06 Aug 2019 01:43:26 +0200

This paper mainly introduces the message pop-up dialog box commonly used in PyQt interface implementation, the input box that provides user input, and the file dialog box that opens file to get file/directory path.Before learning about these three controls, think about the main scenarios they use:

1. Message pop-up dialog box.Programs that encounter problems need to exit. Error prompts need to pop up, risks that program execution may pose, warning windows need to pop up to prompt users for further execution, and so on.

2. User input box.Common program branches, yes/no, etc., that let users choose to execute.

3. File dialog box.Get the full path to a local file or folder or even open the file directly to display the contents of the file.

This paper mainly introduces the main scenarios of these three controls.

QMessageBox: Pop-up dialog control

QMessageBox is a generic pop-up dialog box that displays messages and allows users to feedback on them by clicking different standard buttons.There are many types of pop-up dialogs, such as prompt, warning, error, inquiry, about, and so on.These different types of QMessageBox dialogs are just displayed with different icons and the same functionality.

Common methods in the QMessageBox class

information(QWdiget parent,title,text,buttons,defaultButton): Pop up the message dialog box.

question(QWidget parent,title,text,buttons,defaultButton): Pop up the Q&A dialog box

warning(QWidget parent,title,text,buttons,defaultButton): Pop up a warning dialog box

critical(QWidget parent,title,text,buttons,defaultButton): Pop up serious error dialog

about(QWidget parent,title,text): Pop up about conversation

The parameters are explained as follows:

Parent: The specified parent window control.

Title: Indicates the title of the dialog.

Text: Represents the text of a dialog box.

Buttons: Represents multiple standard buttons, the default is the ok button.

Default Button means the standard button is selected by default, and the first standard button is selected by default.

The other methods are as follows:

setTitle(): Set title

setText(): Set the body message

setIcon(): Set the picture of the pop-up dialog

Standard button type for QMessageBox

QMessage.Ok agrees to the operation, QMessage.Cancel cancels the operation, QMessage.Yes agrees to the operation, QMessage.No cancels the operation, QMessage.Abort terminates the operation, QMessage.Retry retries the operation, and QMessage.Ignore ignores the operation

5 Common Message Dialogs and Their Display Effects

(1) Message dialog box to inform the user about prompt information

* QMessageBox.information(self,'Message Prompt Dialog','Turn right ahead to your destination', QMessageBox.Yes | QMessageBox.No)

(2) Question dialog box, which is used to tell users about the question message.

QMessageBox.question(self,'Question Dialog','Do you want to continue testing?", QMessageBox.Yes | QMessageBox.No)

(3) Warning dialog box to tell users about unusual error messages.

QMessageBox.warning(self,'Warning Dialog','Continuing execution will cause the system to restart. Are you sure you want to continue?", QMessageBox.Yes | QMessageBox.No)

(4) Serious error dialog box, which tells users about serious error messages.

QMessageBox.critical(self,'serious error dialog','array out of bounds, program exits abnormally', QMessageBox.Yes | QMessageBox.No)

(5) About dialogs

QMessageBox.about(self,'About Dialog','Your Windows System is DOS1.0')

The complete code of the above program is as follows:

# -*- coding: utf-8 -*-

import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(431, 166)
        self.pushButton = QtWidgets.QPushButton(Form)
        self.pushButton.setGeometry(QtCore.QRect(160, 50, 91, 41))
        font = QtGui.QFont()
        font.setFamily("YaHei Consolas Hybrid")
        font.setPointSize(10)
        self.pushButton.setFont(font)
        self.pushButton.setObjectName("pushButton")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Dialog box"))
        self.pushButton.setText(_translate("Form", "Pop-up Dialog"))

class MyMainForm(QMainWindow, Ui_Form):
    def __init__(self, parent=None):
        super(MyMainForm, self).__init__(parent)
        self.setupUi(self)
        self.pushButton.clicked.connect(self.showMsg)

    def showMsg(self):
        QMessageBox.information(self, 'Message Prompt Dialog','Turn right ahead to your destination',QMessageBox.Yes | QMessageBox.No,QMessageBox.Yes)
        QMessageBox.question(self, "Question Dialog", "Do you want to continue testing?", QMessageBox.Yes | QMessageBox.No)
        QMessageBox.warning(self, "alert", "Continuing will result in a system restart. Are you sure you want to continue?", QMessageBox.Yes | QMessageBox.No)
        QMessageBox.critical(self, "Serious Error Dialog", "Array out of bounds, program exited abnormally", QMessageBox.Yes | QMessageBox.No,)
        QMessageBox.about(self, "CAboutDlg", "Your Windows System is DOS1.0")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    myWin = MyMainForm()
    myWin.show()
    sys.exit(app.exec_())

QInputDialog Standard Dialog Control

The QInputDialog control is a standard dialog box for getting user input information. The QInputDialog control can provide numeric, string input or drop-down list selection.

For the use of QInputDialog dialog control, we mainly consider two issues: 1, how to pop up the dialog box for user input, 2, how to get user input.

Common QInputDialog methods:

getint(): Get standard integer input from the control

getDouble(): Get standard floating point input from the control

getText(): Get standard string input from the control

getItem(): Get the option input from the list from the control

Description: QInputDialog control

The complete code is as follows:

# -*- coding: utf-8 -*-

import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox,QInputDialog

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(382, 190)
        font = QtGui.QFont()
        font.setPointSize(9)
        font.setBold(False)
        font.setWeight(50)
        Form.setFont(font)
        self.GetIntlineEdit = QtWidgets.QLineEdit(Form)
        self.GetIntlineEdit.setGeometry(QtCore.QRect(150, 30, 150, 31))
        self.GetIntlineEdit.setText("")
        self.GetIntlineEdit.setObjectName("GetIntlineEdit")
        self.GetstrlineEdit = QtWidgets.QLineEdit(Form)
        self.GetstrlineEdit.setGeometry(QtCore.QRect(150, 80, 150, 31))
        self.GetstrlineEdit.setObjectName("GetstrlineEdit")
        self.GetItemlineEdit = QtWidgets.QLineEdit(Form)
        self.GetItemlineEdit.setGeometry(QtCore.QRect(150, 130, 150, 31))
        self.GetItemlineEdit.setObjectName("GetItemlineEdit")
        self.getIntButton = QtWidgets.QPushButton(Form)
        self.getIntButton.setGeometry(QtCore.QRect(50, 30, 80, 31))
        self.getIntButton.setObjectName("getIntButton")
        self.getStrButton = QtWidgets.QPushButton(Form)
        self.getStrButton.setGeometry(QtCore.QRect(50, 80, 80, 31))
        self.getStrButton.setObjectName("getStrButton")
        self.getItemButton = QtWidgets.QPushButton(Form)
        self.getItemButton.setGeometry(QtCore.QRect(50, 130, 80, 31))
        self.getItemButton.setObjectName("getItemButton")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "QInputDialog Example"))
        self.getIntButton.setText(_translate("Form", "Get Integer"))
        self.getStrButton.setText(_translate("Form", "Get String"))
        self.getItemButton.setText(_translate("Form", "Get List Options"))

class MyMainForm(QMainWindow, Ui_Form):
    def __init__(self, parent=None):
        super(MyMainForm, self).__init__(parent)
        self.setupUi(self)
        self.getIntButton.clicked.connect(self.getInt)
        self.getStrButton.clicked.connect(self.getStr)
        self.getItemButton.clicked.connect(self.getItem)

    def getInt(self):
        num, ok = QInputDialog.getInt(self, 'Integer input dialog', 'Input Number')
        if ok and num:
           self.GetIntlineEdit.setText(str(num))

    def getStr(self):
        text, ok=QInputDialog.getText(self, 'Text Input Dialog', 'Enter name:')
        if ok and text:
            self.GetstrlineEdit.setText(str(text))

    def getItem(self):
        items=('C', 'C++', 'C#', 'JAva', 'Python')
        item, ok=QInputDialog.getItem(self, "select input dialog", 'Language List', items, 0, False)
        if ok and item:
            self.GetItemlineEdit.setText(str(item))

if __name__ == "__main__":
    app = QApplication(sys.argv)
    myWin = MyMainForm()
    myWin.show()
    sys.exit(app.exec_())

Key Code Introduction:

QInputDialog.getInt (self,'Integer input dialog','Input number') ->Input integer dialog box

QInputDialog.getText (self,'Text Input Dialog','Enter Name:') ->Enter String Dialog

QInputDialog.getItem (self,'select input dialog','language list', items, 0, False)->Drop-down list selection dialog

QFileDialog File Dialog

QFileDialog is a standard dialog box for opening and saving files.There are two scenarios to consider when using the QFileDialog control: using the control to provide the user with a directory or file selection and to save the path to the directory or file selection.Simply put, it implements something like word/Notepad++ file opening.as follows

For the above scenarios, the main ways to implement the QFileDialog control are as follows:

QFileDialog.getOpenFileName(): Get a single file path

QFileDialog.getOpenFileNames(): Get multiple file paths

QFileDialog.getExistingDirectory(): Get folder path

The complete code is as follows:

# -*- coding: utf-8 -*-

import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox,QInputDialog,QFileDialog

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(443, 120)
        self.widget = QtWidgets.QWidget(Form)
        self.widget.setGeometry(QtCore.QRect(50, 40, 301, 25))
        self.widget.setObjectName("widget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.widget)
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.openFileButton = QtWidgets.QPushButton(self.widget)
        self.openFileButton.setObjectName("openFileButton")
        self.horizontalLayout.addWidget(self.openFileButton)
        self.filePathlineEdit = QtWidgets.QLineEdit(self.widget)
        self.filePathlineEdit.setObjectName("filePathlineEdit")
        self.horizontalLayout.addWidget(self.filePathlineEdit)

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "QFileDialog Open file example"))
        self.openFileButton.setText(_translate("Form", "Open File"))

class MyMainForm(QMainWindow, Ui_Form):
    def __init__(self, parent=None):
        super(MyMainForm, self).__init__(parent)
        self.setupUi(self)
        self.openFileButton.clicked.connect(self.openFile)

    def openFile(self):
        get_directory_path = QFileDialog.getExistingDirectory(self,
                                    "Select the specified folder",
                                    "C:/")
        self.filePathlineEdit.setText(str(get_directory_path))

        get_filename_path, ok = QFileDialog.getOpenFileName(self,
                                    "Select a single file",
                                   "C:/",
                                    "All Files (*);;Text Files (*.txt)")
        if ok:
            self.filePathlineEdit.setText(str(get_filename_path))

        get_filenames_path, ok = QFileDialog.getOpenFileNames(self,
                                    "Select Multiple Files",
                                   "C:/",
                                    "All Files (*);;Text Files (*.txt)")
        if ok:
            self.filePathlineEdit.setText(str(' '.join(get_filenames_path)))

if __name__ == "__main__":
    app = QApplication(sys.argv)
    myWin = MyMainForm()
    myWin.show()
    sys.exit(app.exec_())

Introduction to key codes

QFileDialog.getOpenFileName(self,'Select a single file','C:/','All Files (*),'Text Files (*.txt)') ->Get an absolute path to a single specified file

The getOpenFileName() parameter description:

First parameter: used to specify the parent component

Second parameter: dialog title

The third parameter is the directory that opens by default when the dialog box is displayed."." denotes the directory where the current program is located and "/" denotes the root directory under the current disk.

Fourth parameter: File extension filter in dialog box.All Files (*). Text Files (*.txt) indicates that you can select all file types or only show file types with the.Txt suffix.

QFileDialog.getExistingDirectory(self,'Select Specified Folder','C:/') ->Get the absolute path to the specified folder

QFileDialog.getOpenFileNames(self,'Select multiple files','C:/','All Files (*),'Text Files (*.txt)') ->Get absolute paths to multiple specified files

Summary

This paper introduces the basic usage of message pop-up dialog, user input dialog and file open dialog.Content covers the basic usage scenarios of these three types of controls.You can start trying.

Topics: PHP Windows Java Python