[pyqt5 QT designer] dialog series

Standard input dialog series:

Main module

from PyQt5.QtWidgets import QInputDialog

The effect is as follows:

Full code:

from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, QLabel, QInputDialog, QTextBrowser,QGridLayout)
import sys
from PyQt5.QtGui import QIcon


class Example(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setGeometry(500,500,500,500)
        self.setWindowTitle("Standard input dialog box")
        self.setWindowIcon(QIcon("11.ico"))
        gridLayout = QGridLayout()
        self.lb11 = QLabel("Full name:")
        self.lb12 = QLabel("xiong")
        self.btn1 = QPushButton("Name modification")
        gridLayout.addWidget(self.lb11,0,0,1,1)
        gridLayout.addWidget(self.lb12,0,1,1,1)
        gridLayout.addWidget(self.btn1,0,2,1,1)
        self.lb21 = QLabel("Age:")
        self.lb22 = QLabel("25")
        self.btn2 = QPushButton("Modified age")
        gridLayout.addWidget(self.lb21, 1, 0, 1, 1)
        gridLayout.addWidget(self.lb22, 1, 1, 1, 1)
        gridLayout.addWidget(self.btn2, 1, 2, 1, 1)
        self.lb31 = QLabel("Gender:")
        self.lb32 = QLabel("male")
        self.btn3 = QPushButton("Gender modification")
        gridLayout.addWidget(self.lb31, 2, 0, 1, 1)
        gridLayout.addWidget(self.lb32, 2, 1, 1, 1)
        gridLayout.addWidget(self.btn3, 2, 2, 1, 1)
        self.lb41 = QLabel("Height ( cm): ")
        self.lb42 = QLabel("177.0")
        self.btn4 = QPushButton("Modify height")
        gridLayout.addWidget(self.lb41, 3, 0, 1, 1)
        gridLayout.addWidget(self.lb42, 3, 1, 1, 1)
        gridLayout.addWidget(self.btn4, 3, 2, 1, 1)
        self.lb51 = QLabel("essential information:")
        self.textBrowser = QTextBrowser()
        self.btn5 = QPushButton("Modify information")
        gridLayout.addWidget(self.lb51, 4, 0, 1, 1)
        gridLayout.addWidget(self.textBrowser, 5, 0, 1, 3)
        gridLayout.addWidget(self.btn5, 4, 2, 1, 1)

        self.setLayout(gridLayout)

        self.btn1.clicked.connect(self.showDialog)
        self.btn2.clicked.connect(self.showDialog)
        self.btn3.clicked.connect(self.showDialog)
        self.btn4.clicked.connect(self.showDialog)
        self.btn5.clicked.connect(self.showDialog)

    def showDialog(self):
        sender = self.sender()
        if sender == self.btn1:
            text , ok = QInputDialog.getText(self,"Modify name!","Please enter your name:")
            if ok:
                self.lb12.setText(text)
        elif sender == self.btn2:
            text, ok = QInputDialog.getInt(self, "Modify age!", "Please enter age:",min=1)
            if ok:
                self.lb22.setText(str(text))
        elif sender == self.btn3:
            text, ok = QInputDialog.getItem(self, "Modify gender!", "Please enter gender:",["male","female","Simon?"])
            if ok:
                self.lb32.setText(text)
        elif sender == self.btn4:
            text, ok = QInputDialog.getDouble(self, "Modify height!", "Please enter height:",min=10.0)
            if ok:
                self.lb42.setText(str(text))
        elif sender == self.btn5:
            text, ok = QInputDialog.getMultiLineText(self, "Modify information!", "Please enter basic information:")
            if ok:
                self.textBrowser.setText(text)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    ex.show()
    sys.exit(app.exec_())

Open the file (QFileDialog), color (QColorDialog), font (QFontDialog) dialog box

The effect is as follows:

Reference resources:

https://zhuanlan.zhihu.com/p/29321561

Full code:

from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, QColorDialog,QFontDialog,QFileDialog,QGridLayout,QTextEdit)
import sys
from PyQt5.QtGui import QIcon


class Example(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setGeometry(500,500,400,300)
        self.setWindowTitle("Standard input dialog box")
        self.setWindowIcon(QIcon("11.ico"))
        gridLayout = QGridLayout()
        self.txtFile = QTextEdit()
        self.fileContent = []
        gridLayout.addWidget(self.txtFile,0,0,3,1)
        self.btn1 = QPushButton("Open file")
        self.btn2 = QPushButton("Select font")
        self.btn3 = QPushButton("Select color")
        gridLayout.addWidget(self.btn1, 0, 1, 1, 1)
        gridLayout.addWidget(self.btn2, 1, 1, 1, 1)
        gridLayout.addWidget(self.btn3, 2, 1, 1, 1)
        self.setLayout(gridLayout)

        self.btn1.clicked.connect(self.openFile)
        self.btn2.clicked.connect(self.choseFont)
        self.btn3.clicked.connect(self.choseColor)

    def openFile(self):
        fname = QFileDialog.getOpenFileName(self,"Open file",'./')
        if fname[0]:
            with open(fname[0],'r+',encoding='utf8',errors="ignore") as f:
                self.fileContent.append(f.read())
                txtCon = "".join(self.fileContent)
                self.txtFile.setText("\n"+txtCon)

    def choseFont(self):
        font , ok = QFontDialog.getFont()
        if ok:
            self.txtFile.setCurrentFont(font)
    def choseColor(self):
        color = QColorDialog.getColor()
        if color.isValid():
            self.txtFile.setTextColor(color)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    ex.show()
    sys.exit(app.exec_())

 Document printing (QPageSetupDialog, QPrintDialog)

The effect is as follows:

Reference resources:

https://zhuanlan.zhihu.com/p/29556459

Full code:

from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, QColorDialog,QFontDialog,QFileDialog,QGridLayout,QTextEdit,QDialog)
import sys
from PyQt5.QtGui import QIcon
from PyQt5.QtPrintSupport import QPageSetupDialog,QPrintDialog,QPrinter,QPrintPreviewDialog


class Example(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()
        self.printer = QPrinter()

    def initUI(self):
        self.setGeometry(500,500,400,300)
        self.setWindowTitle("File print dialog box")
        self.setWindowIcon(QIcon("11.ico"))
        gridLayout = QGridLayout()
        self.txtFile = QTextEdit()
        self.fileContent = []
        gridLayout.addWidget(self.txtFile,0,0,7,1)
        self.btn1 = QPushButton("Open file")
        self.btn2 = QPushButton("Open multiple files")
        self.btn3 = QPushButton("Select font")
        self.btn4 = QPushButton("Select color")
        self.btn5 = QPushButton("Save file")
        self.btn6 = QPushButton("Page setup")
        self.btn7 = QPushButton("Print document")
        gridLayout.addWidget(self.btn1, 0, 1, 1, 1)
        gridLayout.addWidget(self.btn2, 1, 1, 1, 1)
        gridLayout.addWidget(self.btn3, 2, 1, 1, 1)
        gridLayout.addWidget(self.btn4, 3, 1, 1, 1)
        gridLayout.addWidget(self.btn5, 4, 1, 1, 1)
        gridLayout.addWidget(self.btn6, 5, 1, 1, 1)
        gridLayout.addWidget(self.btn7, 6, 1, 1, 1)
        self.setLayout(gridLayout)

        self.btn1.clicked.connect(self.openFile)
        self.btn2.clicked.connect(self.openFiles)
        self.btn3.clicked.connect(self.choseFont)
        self.btn4.clicked.connect(self.choseColor)
        self.btn5.clicked.connect(self.saveFile)
        self.btn6.clicked.connect(self.pageSet)
        self.btn7.clicked.connect(self.printFile)

    def openFile(self):
        fname = QFileDialog.getOpenFileName(self,"Open file",'./')
        if fname[0]:
            with open(fname[0],'r+',encoding='utf8',errors="ignore") as f:
                self.fileContent.append(f.read())
                txtCon = "".join(self.fileContent)
                self.txtFile.setText("\n"+txtCon)

    def openFiles(self):
        fnames = QFileDialog.getOpenFileNames(self,"Open multiple files",'./')
        print(fnames)
        if fnames[0]:
            for fname in fnames[0]:
                with open(fname,'r+',encoding='utf8',errors="ignore") as f:
                    self.fileContent.append(f.read()+"\n")
            txtsCon = "".join(self.fileContent)
            self.txtFile.setText(txtsCon)

    def choseFont(self):
        font , ok = QFontDialog.getFont()
        if ok:
            self.txtFile.setCurrentFont(font)

    def choseColor(self):
        color = QColorDialog.getColor()
        if color.isValid():
            self.txtFile.setTextColor(color)

    def saveFile(self):
        fileName = QFileDialog.getSaveFileName(self,"Save file","./","Text files (*.txt)")
        if fileName[0]:
            with open(fileName[0],'w+',encoding='utf8') as f:
                f.write(self.txtFile.toPlainText())

    def pageSet(self):
        printSetDialog = QPageSetupDialog(self.printer,self)
        printSetDialog.exec_()

    def printFile(self):
        printDialog = QPrintDialog(self.printer,self)
        if QDialog.Accepted == printDialog.exec_():
            self.txtFile.print(self.printer)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    ex.show()
    sys.exit(app.exec_())

Message dialog box (QMessageBox)

The effect is as follows:

 

 

Reference resources:

https://zhuanlan.zhihu.com/p/29795495

Full code:

from PyQt5.QtWidgets import (QApplication, QWidget, QLabel,QPushButton, QMessageBox,QGridLayout,QTextEdit,QCheckBox)
import sys
from PyQt5.QtGui import QIcon,QPixmap


class Example(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setGeometry(500,500,400,200)
        self.setWindowTitle("Standard input dialog box")
        self.setWindowIcon(QIcon("11.ico"))
        gridLayout = QGridLayout()
        self.lb = QLabel("You have chosen. abort!")
        self.btn1 = QPushButton("Tips")
        self.btn2 = QPushButton("inquiry")
        self.btn3 = QPushButton("warning")
        self.btn4 = QPushButton("error")
        self.btn5 = QPushButton("about")
        self.btn6 = QPushButton("about QT")
        gridLayout.addWidget(self.lb,0,0,1,1)
        gridLayout.addWidget(self.btn1,1,0,1,1)
        gridLayout.addWidget(self.btn2,1,1,1,1)
        gridLayout.addWidget(self.btn3,1,2,1,1)
        gridLayout.addWidget(self.btn4,3,0,1,1)
        gridLayout.addWidget(self.btn5,3,1,1,1)
        gridLayout.addWidget(self.btn6,3,2,1,1)
        self.setLayout(gridLayout)

        self.btn1.clicked.connect(self.information_dialog)
        self.btn2.clicked.connect(self.question_dialog)
        self.btn3.clicked.connect(self.warning_dialog)
        self.btn4.clicked.connect(self.critical_dialog)
        self.btn5.clicked.connect(self.about_dialog)
        self.btn6.clicked.connect(self.about_QT_dialog)

    def information_dialog(self):
        reply = QMessageBox.information(self,"Prompt dialog","This is a prompt dialog", QMessageBox.Ok | QMessageBox.Close, QMessageBox.Close)
        if reply == QMessageBox.Ok:
            self.lb.setText("You have chosen. information_dialog Of ok!")
        else:
            self.lb.setText("You have chosen. information_dialog Of close!")

    def question_dialog(self):
        reply = QMessageBox.question(self,"Ask dialog window title!","This is a question dialog...",QMessageBox.Yes|QMessageBox.No|QMessageBox.Cancel,QMessageBox.No)
        if reply == QMessageBox.Yes:
            self.lb.setText("You have chosen. question_dialog Of Yes")
        elif reply == QMessageBox.No:
            self.lb.setText("You have chosen. question_dialog Of No")
        else:
            self.lb.setText("You have chosen. question_dialog Of Cancel")

    def warning_dialog(self):
        # reply = QMessageBox.warning(self,'warning','This is a warning message dialog', QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel, QMessageBox.Save)
        cb = QCheckBox('Do this for all documents')
        msgBox = QMessageBox()
        msgBox.setWindowTitle('warning')
        msgBox.setIcon(QMessageBox.Warning)
        msgBox.setText('This is a warning message dialog')
        msgBox.setInformativeText('Do you want to save the changes?')
        Save = msgBox.addButton('Preservation', QMessageBox.AcceptRole)
        NoSave = msgBox.addButton('cancel', QMessageBox.RejectRole)
        Cancel = msgBox.addButton('No preservation', QMessageBox.DestructiveRole)
        msgBox.setDefaultButton(Save)
        msgBox.setCheckBox(cb)
        cb.stateChanged.connect(self.check)
        reply = msgBox.exec()
        if reply == QMessageBox.AcceptRole:
            self.lb.setText('You chose to save!')
        elif reply == QMessageBox.RejectRole:
            self.lb.setText('You chose to cancel!')
        else:
            self.lb.setText('You chose not to save!')

    def check(self):
        print(self.sender().isChecked())
        if self.sender().isChecked():
            self.lb.setText('You ticked it')
        else:
            self.lb.setText('Why don't you fight again')

    def critical_dialog(self):
        # reply = QMessageBox.critical(self,'error','This is an error message dialog', QMessageBox.Retry | QMessageBox.Abort | QMessageBox.Ignore , QMessageBox.Retry)
        msgBox = QMessageBox()
        msgBox.setWindowTitle('error')
        msgBox.setIcon(QMessageBox.Critical)
        msgBox.setText("This is an error message dialog")
        msgBox.setStandardButtons(QMessageBox.Retry | QMessageBox.Abort | QMessageBox.Ignore)
        msgBox.setDefaultButton(QMessageBox.Retry)
        msgBox.setDetailedText('This is the detailed information: learn programming, I love you!')
        reply = msgBox.exec()

        if reply == QMessageBox.Retry:
            self.lb.setText('You have chosen. Retry!')
        elif reply == QMessageBox.Abort:
            self.lb.setText('You have chosen. Abort!')
        else:
            self.lb.setText('You have chosen. Ignore!')

    def about_dialog(self):
        # msgBox = QMessageBox.about(self,"About dialog titles","This is a dialog about,It's a little red flag of Canada")
        msgBox = QMessageBox(QMessageBox.NoIcon ,"About dialog titles","This is about dialog content...")
        msgBox.setIconPixmap(QPixmap("22.ico"))
        msgBox.exec()

    def about_QT_dialog(self):
        msgBox = QMessageBox.aboutQt(self,"about QT Dialog title for")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    ex.show()
    sys.exit(app.exec_())

 Three password input boxes Input method of

  1. The password entered is not visible;
  2. The input password is visible, but the password is not visible after clicking other controls;
  3. The password entered is not visible. In order to be more secure, the right mouse button is blocked, copy and paste shortcuts are disabled, and the mouse cannot be moved or selected in the password box. Just like when we input QQ password.

The effect is as follows:

 

Reference resources:

https://zhuanlan.zhihu.com/p/30152208

Full code:

 

Progress dialog

The effect is as follows:

Reference resources:

https://zhuanlan.zhihu.com/p/30283367

Full code:

from PyQt5.QtWidgets import (QApplication, QWidget, QLabel,QPushButton, QMessageBox,QGridLayout,QLineEdit,QProgressDialog)
import sys
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import Qt


class Example(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setGeometry(500,500,400,200)
        self.setWindowTitle("Progress dialog")
        self.setWindowIcon(QIcon("11.ico"))
        gridLayout = QGridLayout()
        self.lb = QLabel("Number of documents")
        self.lineEdit = QLineEdit("100000")
        self.btn = QPushButton("start")
        gridLayout.addWidget(self.lb,0,0,1,1)
        gridLayout.addWidget(self.lineEdit,0,1,1,3)
        gridLayout.addWidget(self.btn,1,1,1,1)
        self.setLayout(gridLayout)

        self.btn.clicked.connect(self.startProcess)

    def startProcess(self):
        num = int(self.lineEdit.text())
        process = QProgressDialog(self)
        process.setWindowTitle("Progress dialog for progress bar")
        process.setWindowIcon(QIcon("11.ico"))
        process.setLabelText("In operation...")
        process.setCancelButtonText("cancel")
        process.setMinimumDuration(3)   #Set the minimum duration of the progress bar, if the progress time is less than 3000 ms Will not appear
        process.setWindowModality(Qt.WindowModal)
        process.setRange(0,num)
        for i in range(num):
            process.setValue(i)
            if process.wasCanceled():
                QMessageBox.warning(self,"Download tips","operation failed")
                break
        else:
            process.setValue(num)
            QMessageBox.information(self,"Download tips","Operation succeeded")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    ex.show()
    sys.exit(app.exec_())

Keywords: Python encoding Qt Programming less

Added by universelittle on Mon, 02 Dec 2019 22:58:14 +0200