类实例化以后,不论你怎么都可以调用类的控件,函数里面你可以传参啊
如果不使用类,ui还是一个类,实例化以后,直接调用就行。
面向对象编程,代码多了,最好是分文件的。所以最后实际上很少会再单独写一个函数去调用主界面的控件,都是写成类的形式。
self.setupUi(self)就是对界面初始化
单独Ui文件(ui_form.py)
class Ui_Widget(object):
def setupUi(self, Widget):
if not Widget.objectName():
Widget.setObjectName(u"Widget")
Widget.resize(800, 600)
self.frame = QFrame(Widget)
self.frame.setObjectName(u"frame")
self.frame.setGeometry(QRect(80, 100, 641, 351))
self.frame.setFrameShape(QFrame.StyledPanel)
self.frame.setFrameShadow(QFrame.Raised)
self.tsb = QPushButton(self.frame)
self.tsb.setObjectName(u"tsb")
self.tsb.setGeometry(QRect(60, 40, 82, 28))
self.info = QTextBrowser(self.frame)
self.info.setObjectName(u"info")
self.info.setGeometry(QRect(200, 40, 256, 192))
self.retranslateUi(Widget)
QMetaObject.connectSlotsByName(Widget)
# setupUi
def retranslateUi(self, Widget):
Widget.setWindowTitle(QCoreApplication.translate("Widget", u"Widget", None))
self.tsb.setText(QCoreApplication.translate("Widget", u"PushButton", None))
主程序
# This Python file uses the following encoding: utf-8
import sys
import time
from PySide6.QtWidgets import QApplication, QWidget,QHBoxLayout
from PySide6.QtCore import QThread
from thread import TestSpeed
# Important:
# You need to run the following command to generate the ui_form.py file
# pyside6-uic form.ui -o ui_form.py, or
# pyside2-uic form.ui -o ui_form.py
from ui_form import Ui_Widget
class Widget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.ui = Ui_Widget()
self.ui.setupUi(self)
main_layout=QHBoxLayout()
self.ui.frame.setLayout(main_layout)
main_layout.addWidget(self.ui.tsb)
main_layout.addWidget(self.ui.info)
self.ui.tsb.setText("测速")
self.ui.tsb.clicked.connect(self.speed)
#线程初始化,子线程完成测试后,发信号给主界面。
self.thread = QThread()
self.test_thread=TestSpeed(self)
self.test_thread.moveToThread(self.thread)
self.test_thread._signal.connect(self.reflash)
def speed(self):
self.ui.tsb.setEnabled(False)
self.ui.info.setText('测速中。。。')
self.test_thread.start()
def reflash(self):
self.ui.info.setText('测速完毕')
self.ui.tsb.setEnabled(True)
def setText(Widget):
Widget.ui.info.setText("准备测速")
Widget.ui.tsb.setEnabled(True)
if __name__ == "__main__":
app = QApplication(sys.argv)
widget = Widget()
setText(widget)
widget.show()
sys.exit(app.exec())
子线程:(thread.py)
from PySide6.QtCore import Signal,QThread
import time
#import datetime
class TestSpeed(QThread):
# 通过类成员对象定义信号对象
_signal = Signal()
def __init__(self,parent):
super(TestSpeed, self).__init__()
self.parent=parent
def __del__(self):
self.wait()
def run(self):
time.sleep(1)
for i in range(3):
self.parent.ui.info.append(f"{i+1}秒")
time.sleep(1)
self._signal.emit()
最终效果: