当前位置:网站首页>When initializing with pyqt5, super() and_ init _ () problems faced by the coordinated use of functions, as well as the corresponding learning and solutions
When initializing with pyqt5, super() and_ init _ () problems faced by the coordinated use of functions, as well as the corresponding learning and solutions
2022-07-28 04:47:00 【Worthless life】
Use PyQt5 On initialization ,super() and _ init _ () Problems faced by the coordinated use of functions , And corresponding learning and solutions .
Problem description :
1、 I'm learning PyQt5 when , Want to cooperate with QT Designer The design of the .ui File to design the interface , however , Need to put .ui The file is converted to .py File for use .( If you use pyside , Can be used directly .ui file , But in packaging as a .exe When you file , You need to perform additional operations on these files .)
2、 Due to the conversion to .py Code time , He is with class Class . therefore , In use , When the generated class method needs to be called for the initial session of the interface , It needs to be encapsulated again .
3、 also , In their own actual use QT Designer Design Ui file , And import it as .py When you file , Refer to others' routines to write .py When the file is running , a super(), Because I don't know how to use this function , When copying code , There is always the problem of reporting errors .
4、 So make a note here to learn .
First, give the complete .ui file and Converted .py file
Main window file plot_graph.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>mainWindow</class>
<widget class="QMainWindow" name="mainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>648</height>
</rect>
</property>
<property name="windowTitle">
<string> main window </string>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<layout class="QHBoxLayout" name="horizontalLayout_3">
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QPushButton" name="pushButton_2">
<property name="text">
<string>PushButton</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="pushButton">
<property name="text">
<string>PushButton</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QPushButton" name="pushButton_3">
<property name="text">
<string>PushButton</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="pushButton_4">
<property name="text">
<string>PushButton</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</item>
<item>
<widget class="QPlainTextEdit" name="plainTextEdit">
<property name="minimumSize">
<size>
<width>104</width>
<height>71</height>
</size>
</property>
</widget>
</item>
</layout>
</widget>
</widget>
<resources/>
<connections/>
</ui>
By switching (VScode + plug-in unit PYQT Integration) Later obtained Ui_plot_graph.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'c:\Users\LJ\Desktop\pyQT5\plot_graph.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_mainWindow(object):
def setupUi(self, mainWindow):
mainWindow.setObjectName("mainWindow")
mainWindow.resize(800, 648)
self.centralwidget = QtWidgets.QWidget(mainWindow)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
self.verticalLayout.setObjectName("verticalLayout")
self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
self.horizontalLayout_3.setObjectName("horizontalLayout_3")
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_2.setObjectName("pushButton_2")
self.horizontalLayout.addWidget(self.pushButton_2)
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setObjectName("pushButton")
self.horizontalLayout.addWidget(self.pushButton)
self.horizontalLayout_3.addLayout(self.horizontalLayout)
spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_3.addItem(spacerItem)
self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_3.setObjectName("pushButton_3")
self.horizontalLayout_2.addWidget(self.pushButton_3)
self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_4.setObjectName("pushButton_4")
self.horizontalLayout_2.addWidget(self.pushButton_4)
self.horizontalLayout_3.addLayout(self.horizontalLayout_2)
self.verticalLayout.addLayout(self.horizontalLayout_3)
self.plainTextEdit = QtWidgets.QPlainTextEdit(self.centralwidget)
self.plainTextEdit.setMinimumSize(QtCore.QSize(104, 71))
self.plainTextEdit.setObjectName("plainTextEdit")
self.verticalLayout.addWidget(self.plainTextEdit)
mainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(mainWindow)
QtCore.QMetaObject.connectSlotsByName(mainWindow)
def retranslateUi(self, mainWindow):
_translate = QtCore.QCoreApplication.translate
mainWindow.setWindowTitle(_translate("mainWindow", " main window "))
self.pushButton_2.setText(_translate("mainWindow", "PushButton"))
self.pushButton.setText(_translate("mainWindow", "PushButton"))
self.pushButton_3.setText(_translate("mainWindow", "PushButton"))
self.pushButton_4.setText(_translate("mainWindow", "PushButton"))
Window file plot_graph1.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Form</class>
<widget class="QWidget" name="Form">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>400</width>
<height>300</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<widget class="QPushButton" name="pushButton">
<property name="text">
<string>PushButton</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QPushButton" name="pushButton_3">
<property name="text">
<string>PushButton</string>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QPushButton" name="pushButton_2">
<property name="text">
<string>PushButton</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QPushButton" name="pushButton_4">
<property name="text">
<string>PushButton</string>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>
Converted window file Ui_plot_graph1.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'c:\Users\LJ\Desktop\pyQT5\plot_graph1.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(400, 300)
self.gridLayout = QtWidgets.QGridLayout(Form)
self.gridLayout.setObjectName("gridLayout")
self.pushButton = QtWidgets.QPushButton(Form)
self.pushButton.setObjectName("pushButton")
self.gridLayout.addWidget(self.pushButton, 0, 0, 1, 1)
self.pushButton_3 = QtWidgets.QPushButton(Form)
self.pushButton_3.setObjectName("pushButton_3")
self.gridLayout.addWidget(self.pushButton_3, 0, 1, 1, 1)
self.pushButton_2 = QtWidgets.QPushButton(Form)
self.pushButton_2.setObjectName("pushButton_2")
self.gridLayout.addWidget(self.pushButton_2, 1, 0, 1, 1)
self.pushButton_4 = QtWidgets.QPushButton(Form)
self.pushButton_4.setObjectName("pushButton_4")
self.gridLayout.addWidget(self.pushButton_4, 1, 1, 1, 1)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.pushButton.setText(_translate("Form", "PushButton"))
self.pushButton_3.setText(_translate("Form", "PushButton"))
self.pushButton_2.setText(_translate("Form", "PushButton"))
self.pushButton_4.setText(_translate("Form", "PushButton"))
notes : The top two .py The files are Respective ui The files are generated automatically , By running these two scripts, there will be no square sound ( Just two classes , There is no other operation ).
therefore , In order to call by ui Generate .py Interface , Need to write a new .py To implement these two different interfaces , The specific code is as follows .
import sys
from PyQt5.QtWidgets import QApplication , QMainWindow
from PyQt5.QtWidgets import QWidget
from Ui_plot_graph import Ui_mainWindow # Import custom Created main window (mainwidget) Design interface for
from Ui_plot_graph1 import Ui_Form # Import custom Created window (widget) Design interface for
# notes : Ui_mainWindow It can be replaced with any name , But it must be adopt mainWindow.ui The generated class
# Class initialized by main window
class MyMainWindow(QMainWindow,Ui_mainWindow):
def __init__(self):
#super(MyMainWindow, self).__init__() # call MyMainWindow The parent class of constructs the initialization method
QMainWindow.__init__(self) # call QMainWindow The parent class constructs the initialization method
#def __init__(self,parent=None):
#super(MyMainWindow, self).__init__(parent=None) # call MyMainWindow The parent class of constructs the initialization method
self.setupUi(self) # initialization , Call the parent class (Ui_mainWindow) Of setupUi() Method
# notes : Ui_Form It can be replaced with any name , But it must be adopt MyWidget.ui The generated class
# Window initialization class
class MyWidget(QMainWindow,Ui_Form):
def __init__(self):
super(QMainWindow, self).__init__() # call MyMainWindow The parent class of constructs the initialization method
#def __init__(self,parent=None):
#super(MyMainWindow, self).__init__(parent=None) # call MyMainWindow The parent class of constructs the initialization method
self.setupUi(self) # initialization , Call the parent class (Ui_mainWindow) Of setupUi() Method
# The wrong sample , Here is the design .UI When you file , The class name of the window is used , But at runtime , The inherited classes are The class name of the main window QMainWindow. And that leads to mistakes .
""" class MyWidget(QMainWindow,Ui_Form): def __init__(self): super(QMainWindow, self).__init__() # call MyMainWindow The parent class of constructs the initialization method #def __init__(self,parent=None): #super(MyMainWindow, self).__init__(parent=None) # call MyMainWindow The parent class of constructs the initialization method self.setupUi(self) # initialization , Call the parent class (Ui_mainWindow) Of setupUi() Method """
if __name__=="__main__":
app = QApplication(sys.argv) # QT Self initialization ,sys.argv It's a command line argument notes : This has to be placed in QT Use the front
myWin = MyWidget() # Load one UI file , Also on UI Initialize the interface
myWin.show() # Show UI Interface
sys.exit(app.exec_())
Main realization idea :
1、 Import two converted (class) class ( One is the class of the main window 、 One is the class of window )
from Ui_plot_graph import Ui_mainWindow # Import custom Created main window (mainwidget) Design interface for
from Ui_plot_graph1 import Ui_Form # Import custom Created window (widget) Design interface for
2、 Encapsulate these two classes respectively , Realize the initialization of the interface
# Class initialized by main window
class MyMainWindow(QMainWindow,Ui_mainWindow):
def __init__(self):
#super(MyMainWindow, self).__init__() # call MyMainWindow The parent class of constructs the initialization method
QMainWindow.__init__(self) # call QMainWindow The parent class constructs the initialization method
#def __init__(self,parent=None):
#super(MyMainWindow, self).__init__(parent=None) # call MyMainWindow The parent class of constructs the initialization method
self.setupUi(self) # initialization , Call the parent class (Ui_mainWindow) Of setupUi() Method
# Window initialization class
class MyWidget(QWidget,Ui_Form):
def __init__(self):
super(QWidget, self).__init__() # call MyMainWindow The parent class of constructs the initialization method
#def __init__(self,parent=None):
#super(MyMainWindow, self).__init__(parent=None) # call MyMainWindow The parent class of constructs the initialization method
self.setupUi(self) # initialization , Call the parent class (Ui_mainWindow) Of setupUi() Method
There are two different interface packages , You can see , One of the encapsulated classes inherits two first The contents of the parent class , Namely ( Corresponding ui Window type parent ,UI The generated class ).
_ init _(self) function , Itself is when you call this function , First, execute this initialization method internally , This does not require additional calls .
therefore , Here you need to package _ init _ (self) Its own initialization process , By inheritance QMainWindow( Main window class )or QMainWindow ( Window class ), There are some initialization contents . therefore , The encapsulated class first needs to call The initialization method of the parent class is completed Encapsulate the initialization content of the class , also , You also need to call from .ui The file is converted to .py File class . Finally complete the initialization of the interface .
Here's the thing to notice , When calling the method of the parent class or initializing the parent class , There are several ways .
# Mode one
QMainWindow.__init__(self) # call QMainWindow The parent class constructs the initialization method
# Mode two
super(MyMainWindow, self).__init__() # call MyMainWindow The parent class of constructs the initialization method
# Mode three ( This way of initialization can also be realized )
super(QMainWindow, self).__init__() # call MyMainWindow The parent class of constructs the initialization method
When writing encapsulated classes , First, make it clear , It is when we design .ui When you file , It uses QMainWindow still QWidget. ( Because when I started learning , Without systematic learning , Actually pyQT I haven't found any good learning materials , And see super() Function doesn't know how to use . So I always encounter various problems , Let's talk a little more here .)
Last , stay Encapsulated classes _ init _ call ui Generated interface content , Finally, initialize the interface .
self.setupUi(self) # initialization , Call the parent class (Ui_Form) Of setupUi() Method
Last , Instantiate the encapsulated class .
if __name__=="__main__":
app = QApplication(sys.argv) # QT Self initialization ,sys.argv It's a command line argument notes : This has to be placed in QT Use the front
myWin = MyMainWindow() # Load one MyMainWindow Of UI file , Also on UI Instantiate the interface , Initialization interface data .
myWin.show() # Show UI Interface ( Here is the method of inheriting the parent class to call )
sys.exit(app.exec_())
边栏推荐
- 01 node express system framework construction (express generator)
- Destructor of member function
- printf()打印char* str
- bubble sort
- [函数文档] torch.histc 与 paddle.histogram 与 numpy.histogram
- 【sylar】实战篇-基于 redis 的参数查询服务
- [Hongke technology] Application of network Multimeter in data center
- Reading of papers on "towards generative aspect based sentimental analysis"
- Pyqt based grouping tool
- If mongoose exists, it will be updated; if it does not exist, it will be added
猜你喜欢

Leetcode 18. sum of four numbers

Important SQL server functions - date functions

could only be written to 0 of the 1 minReplication nodes. There are 0 datanode(s) running and 0 node

Rendering process, how the code becomes a page (2)

机器人教育在STEM课程中的设计研究

Artificial intelligence and RPA technology application (I) -rpa Hongji product introduction, designer interface function explanation

Phpstorm2022 connect to the database

Bio annotation of emotion analysis aste triples extraction

What SaaS architecture design do you need to know?
![(2.4) [service Trojan -slimftp] introduction and use](/img/72/d3e46a820796a48b458cd2d0a18f8f.png)
(2.4) [service Trojan -slimftp] introduction and use
随机推荐
Gerrit operation - rollback a patch_ set
提升学生群体中的STEAM教育核心素养
Attempt method in laravel user authentication
Harmony's Application on the shelves reported an error. The solution of "please use the API of the released version to develop the application and apply for listing"
High number_ Chapter 4__ Curvilinear integral_ Exercise solution
X Book Keyword Search
01-Node-Express系统框架搭建(express-generator)
Cmake usage base summary
transform: failed to synchronize: cudaErrorAssert: device-side assert triggered
全方位分析STEAM和创客教育的差异化
【sylar】框架篇-Chapter24-支持业务模块化
Object locking in relational database transactions
np. The data returned from delete details is the data after deleting the specified dimension
System clock failure of database fault tolerance
[Sylar] framework -chapter9-hook module
The first artificial intelligence security competition starts. Three competition questions are waiting for you to fight
Important SQL server functions - other functions
Simple summary of Modbus Protocol
Reading the paper "learning span level interactions for aspect sentimental triple extraction"
字符串0123456789abcdef,子串(非空且非同串本身)的个数是多少【杭州多测师】【杭州多测师_王sir】...