当前位置:网站首页>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_())
边栏推荐
- [Sylar] framework -chapter15 stream module
- Important SQL server functions - date functions
- [Sylar] framework -chapter14 tcpserver module
- 全方位分析STEAM和创客教育的差异化
- 你必需要了解的saas架构设计?
- alter和confirm,prompt的区别
- MySQL: data types and operators
- 阿里巴巴面试题【杭州多测师】【杭州多测师_王sir】
- Wang Shuang assembly language detailed learning notes 3: registers (memory access)
- Printf() print char* str
猜你喜欢

Internet of things industrial serial port to WiFi module wireless routing WiFi module selection

Space complexity calculation super full sorting!! (calculation of hand tearing complexity

Wang Shuang assembly language detailed learning notes 3: registers (memory access)

Password key hard coding check

excel实战应用案例100讲(十一)-Excel插入图片小技巧

Real intelligence has been certified by two of the world's top market research institutions and has entered the global camp of excellence

Mac installs mysql5.7 through brew

王爽汇编语言详细学习笔记三:寄存器(内存访问)

Is low code the future of development? On low code platform

MySQL: data types and operators
随机推荐
【sylar】框架篇-Chapter20-守护进程模块
excel实战应用案例100讲(十一)-Excel插入图片小技巧
Youxuan database participated in the compilation of the Research Report on database development (2022) of the China Academy of communications and communications
Leetcode 15. sum of three numbers
[Hongke technology] Application of network Multimeter in data center
启发国内学子学习少儿机器人编程教育
字符串0123456789abcdef,子串(非空且非同串本身)的个数是多少【杭州多测师】【杭州多测师_王sir】...
[II. Mobile web page development] 2D & 3D conversion and animation, mobile terminal layout, responsive layout
set与list性能对比
【sylar】框架篇-Chapter15-Stream 模块
mysql分区表改造
Artificial intelligence and RPA technology application (I) -rpa Hongji product introduction, designer interface function explanation
NAT基本原理与私有IP
Is low code the future of development? On low code platform
Strlen introduction, and the difference between sizeof
Constructor of member function
[Sylar] framework -chapter15 stream module
机器人教育在STEM课程中的设计研究
Reading of seq2path: generating sentimental tuples as paths of a tree
Niuke, convert string to integer