search
HomeBackend DevelopmentPHP Tutorialpython3+PyQt5+Qt Designer implements extended dialog box

python3+PyQt5+Qt Designer implements extended dialog box

Apr 20, 2018 pm 01:36 PM
designerdialog box

This article mainly introduces the extension dialog box implemented by python3 PyQt5 Qt Designer in detail. It has certain reference value. Interested friends can refer to it.

This article is a review of "Python Qt GUI Quick The extended dialog box example Find and replace in Chapter 9 of "Programming" is rewritten using Python3 PyQt5 Qt Designer.

The first part does not borrow Qt Designer and is completely implemented in code.
The second part uses Qt Designer to implement quickly.

Part one:


##

import sys
from PyQt5.QtCore import Qt,pyqtSignal
from PyQt5.QtWidgets import (QApplication, QCheckBox, QDialog, QFrame,
    QGridLayout, QHBoxLayout, QLabel, QLayout, QLineEdit,
    QPushButton, QVBoxLayout)



class FindAndReplaceDlg(QDialog):
  find = pyqtSignal(str,bool,bool,bool,bool,bool)
  replace = pyqtSignal(str,str,bool,bool,bool,bool,bool)   

  def __init__(self, parent=None):
    super(FindAndReplaceDlg, self).__init__(parent)

    findLabel = QLabel("Find &what:")
    self.findLineEdit = QLineEdit()
    findLabel.setBuddy(self.findLineEdit)
    replaceLabel = QLabel("Replace w&ith:")
    self.replaceLineEdit = QLineEdit()
    replaceLabel.setBuddy(self.replaceLineEdit)
    self.caseCheckBox = QCheckBox("&Case sensitive")
    self.wholeCheckBox = QCheckBox("Wh&ole words")
    self.wholeCheckBox.setChecked(True)
    self.moreFrame = QFrame()
    self.moreFrame.setFrameStyle(QFrame.StyledPanel|QFrame.Sunken)
    self.backwardsCheckBox = QCheckBox("Search &Backwards")
    self.regexCheckBox = QCheckBox("Regular E&xpression")
    self.ignoreNotesCheckBox = QCheckBox("Ignore foot&notes "
                          "and endnotes")
    line = QFrame()
    line.setFrameStyle(QFrame.VLine|QFrame.Sunken)
    self.findButton = QPushButton("&Find")
    self.replaceButton = QPushButton("&Replace")
    closeButton = QPushButton("Close")
    self.moreButton = QPushButton("&More")
    self.moreButton.setCheckable(True)


    gridLayout = QGridLayout()
    gridLayout.addWidget(findLabel, 0, 0)
    gridLayout.addWidget(self.findLineEdit, 0, 1)
    gridLayout.addWidget(replaceLabel, 1, 0)
    gridLayout.addWidget(self.replaceLineEdit, 1, 1)
    frameLayout = QVBoxLayout()
    frameLayout.addWidget(self.backwardsCheckBox)
    frameLayout.addWidget(self.regexCheckBox)
    frameLayout.addWidget(self.ignoreNotesCheckBox)
    self.moreFrame.setLayout(frameLayout)
    leftLayout = QVBoxLayout()
    leftLayout.addLayout(gridLayout)
    leftLayout.addWidget(self.caseCheckBox)
    leftLayout.addWidget(self.wholeCheckBox)
    leftLayout.addWidget(self.moreFrame)
    buttonLayout = QVBoxLayout()
    buttonLayout.addWidget(self.findButton)
    buttonLayout.addWidget(self.replaceButton)
    buttonLayout.addWidget(closeButton)
    buttonLayout.addWidget(self.moreButton)
    buttonLayout.addStretch()
    mainLayout = QHBoxLayout()
    mainLayout.addLayout(leftLayout)
    mainLayout.addWidget(line)
    mainLayout.addLayout(buttonLayout)
    self.setLayout(mainLayout)

    self.moreFrame.hide()
    mainLayout.setSizeConstraint(QLayout.SetFixedSize)

    self.moreButton.toggled[bool].connect(self.setvisible)


    self.findLineEdit.textEdited.connect(self.updateUi)
    self.findButton.clicked.connect(self.findClicked)
    self.replaceButton.clicked.connect(self.replaceClicked)

    self.updateUi()
    self.setWindowTitle("Find and Replace")

  def setvisible(self,YN):
    self.moreFrame.setVisible(YN)


  def findClicked(self):
    self.find.emit(self.findLineEdit.text(),
        self.caseCheckBox.isChecked(),
        self.wholeCheckBox.isChecked(),
        self.backwardsCheckBox.isChecked(),
        self.regexCheckBox.isChecked(),
        self.ignoreNotesCheckBox.isChecked())


  def replaceClicked(self):
    self.replace.emit(self.findLineEdit.text(),
        self.replaceLineEdit.text(),
        self.caseCheckBox.isChecked(),
        self.wholeCheckBox.isChecked(),
        self.backwardsCheckBox.isChecked(),
        self.regexCheckBox.isChecked(),
        self.ignoreNotesCheckBox.isChecked())


  def updateUi(self):
    enable = self.findLineEdit.text()
    self.findButton.setEnabled(bool(enable))
    self.replaceButton.setEnabled(bool(enable))


if __name__ == "__main__":

  def find(what, *args):
    print("Find {0} {1}".format(what, [x for x in args]))

  def replace(old, new, *args):
    print("Replace {0} with {1} {2}".format(
       old, new, [x for x in args]))

  app = QApplication(sys.argv)
  form = FindAndReplaceDlg()
  form.find.connect(find)
  form.replace.connect(replace)    
  form.show()
  app.exec_()


Part two:

/home/yrd/eric_workspace/chap09/findandreplacedlg/Ui_findandreplacedlg.py


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

# Form implementation generated from reading ui file '/home/yrd/eric_workspace/chap09/findandreplacedlg/findandreplacedlg.ui'
#
# Created by: PyQt5 UI code generator 5.7
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_FindAndReplaceDlg(object):
  def setupUi(self, FindAndReplaceDlg):
    FindAndReplaceDlg.setObjectName("FindAndReplaceDlg")
    FindAndReplaceDlg.resize(355, 274)
    self.mainlayout = QtWidgets.QHBoxLayout(FindAndReplaceDlg)
    self.mainlayout.setSizeConstraint(QtWidgets.QLayout.SetFixedSize)
    self.mainlayout.setContentsMargins(9, 9, 9, 9)
    self.mainlayout.setSpacing(6)
    self.mainlayout.setObjectName("mainlayout")
    self.vboxlayout = QtWidgets.QVBoxLayout()
    self.vboxlayout.setContentsMargins(0, 0, 0, 0)
    self.vboxlayout.setSpacing(6)
    self.vboxlayout.setObjectName("vboxlayout")
    self.gridlayout = QtWidgets.QGridLayout()
    self.gridlayout.setContentsMargins(0, 0, 0, 0)
    self.gridlayout.setSpacing(6)
    self.gridlayout.setObjectName("gridlayout")
    self.replaceLineEdit = QtWidgets.QLineEdit(FindAndReplaceDlg)
    self.replaceLineEdit.setObjectName("replaceLineEdit")
    self.gridlayout.addWidget(self.replaceLineEdit, 1, 1, 1, 1)
    self.findLineEdit = QtWidgets.QLineEdit(FindAndReplaceDlg)
    self.findLineEdit.setObjectName("findLineEdit")
    self.gridlayout.addWidget(self.findLineEdit, 0, 1, 1, 1)
    self.label_2 = QtWidgets.QLabel(FindAndReplaceDlg)
    self.label_2.setObjectName("label_2")
    self.gridlayout.addWidget(self.label_2, 1, 0, 1, 1)
    self.label = QtWidgets.QLabel(FindAndReplaceDlg)
    self.label.setObjectName("label")
    self.gridlayout.addWidget(self.label, 0, 0, 1, 1)
    self.vboxlayout.addLayout(self.gridlayout)
    self.vboxlayout1 = QtWidgets.QVBoxLayout()
    self.vboxlayout1.setContentsMargins(0, 0, 0, 0)
    self.vboxlayout1.setSpacing(6)
    self.vboxlayout1.setObjectName("vboxlayout1")
    self.caseCheckBox = QtWidgets.QCheckBox(FindAndReplaceDlg)
    self.caseCheckBox.setObjectName("caseCheckBox")
    self.vboxlayout1.addWidget(self.caseCheckBox)
    self.wholeCheckBox = QtWidgets.QCheckBox(FindAndReplaceDlg)
    self.wholeCheckBox.setChecked(True)
    self.wholeCheckBox.setObjectName("wholeCheckBox")
    self.vboxlayout1.addWidget(self.wholeCheckBox)
    self.vboxlayout.addLayout(self.vboxlayout1)
    spacerItem = QtWidgets.QSpacerItem(231, 16, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
    self.vboxlayout.addItem(spacerItem)
    self.moreFrame = QtWidgets.QFrame(FindAndReplaceDlg)
    self.moreFrame.setFrameShape(QtWidgets.QFrame.StyledPanel)
    self.moreFrame.setFrameShadow(QtWidgets.QFrame.Raised)
    self.moreFrame.setObjectName("moreFrame")
    self.vboxlayout2 = QtWidgets.QVBoxLayout(self.moreFrame)
    self.vboxlayout2.setContentsMargins(9, 9, 9, 9)
    self.vboxlayout2.setSpacing(6)
    self.vboxlayout2.setObjectName("vboxlayout2")
    self.backwardsCheckBox = QtWidgets.QCheckBox(self.moreFrame)
    self.backwardsCheckBox.setObjectName("backwardsCheckBox")
    self.vboxlayout2.addWidget(self.backwardsCheckBox)
    self.regexCheckBox = QtWidgets.QCheckBox(self.moreFrame)
    self.regexCheckBox.setObjectName("regexCheckBox")
    self.vboxlayout2.addWidget(self.regexCheckBox)
    self.ignoreNotesCheckBox = QtWidgets.QCheckBox(self.moreFrame)
    self.ignoreNotesCheckBox.setObjectName("ignoreNotesCheckBox")
    self.vboxlayout2.addWidget(self.ignoreNotesCheckBox)
    self.vboxlayout.addWidget(self.moreFrame)
    self.mainlayout.addLayout(self.vboxlayout)
    self.line = QtWidgets.QFrame(FindAndReplaceDlg)
    self.line.setFrameShape(QtWidgets.QFrame.VLine)
    self.line.setFrameShadow(QtWidgets.QFrame.Sunken)
    self.line.setObjectName("line")
    self.mainlayout.addWidget(self.line)
    self.vboxlayout3 = QtWidgets.QVBoxLayout()
    self.vboxlayout3.setContentsMargins(0, 0, 0, 0)
    self.vboxlayout3.setSpacing(6)
    self.vboxlayout3.setObjectName("vboxlayout3")
    self.findButton = QtWidgets.QPushButton(FindAndReplaceDlg)
    self.findButton.setFocusPolicy(QtCore.Qt.NoFocus)
    self.findButton.setObjectName("findButton")
    self.vboxlayout3.addWidget(self.findButton)
    self.replaceButton = QtWidgets.QPushButton(FindAndReplaceDlg)
    self.replaceButton.setFocusPolicy(QtCore.Qt.NoFocus)
    self.replaceButton.setObjectName("replaceButton")
    self.vboxlayout3.addWidget(self.replaceButton)
    self.closeButton = QtWidgets.QPushButton(FindAndReplaceDlg)
    self.closeButton.setFocusPolicy(QtCore.Qt.NoFocus)
    self.closeButton.setObjectName("closeButton")
    self.vboxlayout3.addWidget(self.closeButton)
    self.moreButton = QtWidgets.QPushButton(FindAndReplaceDlg)
    self.moreButton.setFocusPolicy(QtCore.Qt.NoFocus)
    self.moreButton.setCheckable(True)
    self.moreButton.setObjectName("moreButton")
    self.vboxlayout3.addWidget(self.moreButton)
    spacerItem1 = QtWidgets.QSpacerItem(21, 16, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
    self.vboxlayout3.addItem(spacerItem1)
    self.mainlayout.addLayout(self.vboxlayout3)
    self.label_2.setBuddy(self.replaceLineEdit)
    self.label.setBuddy(self.findLineEdit)

    self.retranslateUi(FindAndReplaceDlg)
    self.closeButton.clicked.connect(FindAndReplaceDlg.reject)
    self.moreButton.toggled['bool'].connect(self.moreFrame.setVisible)
    QtCore.QMetaObject.connectSlotsByName(FindAndReplaceDlg)
    FindAndReplaceDlg.setTabOrder(self.findLineEdit, self.replaceLineEdit)
    FindAndReplaceDlg.setTabOrder(self.replaceLineEdit, self.caseCheckBox)
    FindAndReplaceDlg.setTabOrder(self.caseCheckBox, self.wholeCheckBox)
    FindAndReplaceDlg.setTabOrder(self.wholeCheckBox, self.backwardsCheckBox)
    FindAndReplaceDlg.setTabOrder(self.backwardsCheckBox, self.regexCheckBox)
    FindAndReplaceDlg.setTabOrder(self.regexCheckBox, self.ignoreNotesCheckBox)

  def retranslateUi(self, FindAndReplaceDlg):
    _translate = QtCore.QCoreApplication.translate
    FindAndReplaceDlg.setWindowTitle(_translate("FindAndReplaceDlg", "Find and Replace"))
    self.label_2.setText(_translate("FindAndReplaceDlg", "Replace w&ith:"))
    self.label.setText(_translate("FindAndReplaceDlg", "Find &what:"))
    self.caseCheckBox.setText(_translate("FindAndReplaceDlg", "&Case sensitive"))
    self.wholeCheckBox.setText(_translate("FindAndReplaceDlg", "Wh&ole words"))
    self.backwardsCheckBox.setText(_translate("FindAndReplaceDlg", "Search &Backwards"))
    self.regexCheckBox.setText(_translate("FindAndReplaceDlg", "Regular E&xpression"))
    self.ignoreNotesCheckBox.setText(_translate("FindAndReplaceDlg", "Ignore foot&notes and endnotes"))
    self.findButton.setText(_translate("FindAndReplaceDlg", "&Find"))
    self.replaceButton.setText(_translate("FindAndReplaceDlg", "&Replace"))
    self.closeButton.setText(_translate("FindAndReplaceDlg", "Close"))
    self.moreButton.setText(_translate("FindAndReplaceDlg", "&More"))


/home/yrd/ eric_workspace/chap09/findandreplacedlg/findandreplacedlg.py


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

"""
Module implementing FindAndReplaceDlg.
"""

from PyQt5.QtCore import pyqtSlot,pyqtSignal
from PyQt5.QtWidgets import QDialog,QApplication

from Ui_findandreplacedlg import Ui_FindAndReplaceDlg


class FindAndReplaceDlg(QDialog, Ui_FindAndReplaceDlg):
  """
  Class documentation goes here.
  """
  find = pyqtSignal(str,bool,bool,bool,bool,bool)
  replace = pyqtSignal(str,str,bool,bool,bool,bool,bool)   
  def __init__(self, parent=None):
    """
    Constructor

    @param parent reference to the parent widget
    @type QWidget
    """
    super(FindAndReplaceDlg, self).__init__(parent)
    self.setupUi(self)
    self.moreFrame.hide()
    #self.layout().setSizeConstraint(QLayout.SetFixedSize)
    self.updateUi()    

  @pyqtSlot(str)
  def on_findLineEdit_textEdited(self, text):
    """
    Slot documentation goes here.

    @param p0 DESCRIPTION
    @type str
    """
    # TODO: not implemented yet
    self.updateUi()

  @pyqtSlot()
  def on_findButton_clicked(self):
    self.find.emit(self.findLineEdit.text(),
            self.caseCheckBox.isChecked(),
            self.wholeCheckBox.isChecked(),
            self.backwardsCheckBox.isChecked(),
            self.regexCheckBox.isChecked(),
            self.ignoreNotesCheckBox.isChecked())    


  @pyqtSlot()
  def on_replaceButton_clicked(self):
    self.replace.emit(self.findLineEdit.text(),
             self.replaceLineEdit.text(),
             self.caseCheckBox.isChecked(),
             self.wholeCheckBox.isChecked(),
             self.backwardsCheckBox.isChecked(),
             self.regexCheckBox.isChecked(),
             self.ignoreNotesCheckBox.isChecked())

  def updateUi(self):
    enable = self.findLineEdit.text()
    self.findButton.setEnabled(bool(enable))
    self.replaceButton.setEnabled(bool(enable))

if __name__ == "__main__":
  import sys

  def find(what, *args):
    print("Find {0} {1}".format(what, [x for x in args]))

  def replace(old, new, *args):
    print("Replace {0} with {1} {2}".format(
       old, new, [x for x in args]))

  app = QApplication(sys.argv)
  form = FindAndReplaceDlg()
  form.find.connect(find)
  form.replace.connect(replace)
  form.show()
  app.exec_()


Run result:

Related recommendations:


hasattr(), getattr(), setattr(), delattr() functions and sample codes in Python3


The above is the detailed content of python3+PyQt5+Qt Designer implements extended dialog box. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

How can you trace session activity in PHP?How can you trace session activity in PHP?Apr 27, 2025 am 12:10 AM

Tracking user session activities in PHP is implemented through session management. 1) Use session_start() to start the session. 2) Store and access data through the $_SESSION array. 3) Call session_destroy() to end the session. Session tracking is used for user behavior analysis, security monitoring, and performance optimization.

How can you use a database to store PHP session data?How can you use a database to store PHP session data?Apr 27, 2025 am 12:02 AM

Using databases to store PHP session data can improve performance and scalability. 1) Configure MySQL to store session data: Set up the session processor in php.ini or PHP code. 2) Implement custom session processor: define open, close, read, write and other functions to interact with the database. 3) Optimization and best practices: Use indexing, caching, data compression and distributed storage to improve performance.

Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.