一、用QT Designer做出展示图
demo2.ui文件的代码
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>widget</class>
<widget class="QWidget" name="widget">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>1181</width>
<height>1133</height>
</rect>
</property>
<property name="windowTitle">
<string>练习demo</string>
</property>
<widget class="QPushButton" name="pushButton">
<property name="geometry">
<rect>
<x>210</x>
<y>170</y>
<width>93</width>
<height>28</height>
</rect>
</property>
<property name="text">
<string>开启时钟</string>
</property>
</widget>
<widget class="QLabel" name="label">
<property name="geometry">
<rect>
<x>370</x>
<y>180</y>
<width>201</width>
<height>16</height>
</rect>
</property>
<property name="text">
<string>TextLabel</string>
</property>
</widget>
<widget class="QLineEdit" name="lineEdit">
<property name="geometry">
<rect>
<x>220</x>
<y>60</y>
<width>113</width>
<height>21</height>
</rect>
</property>
</widget>
<widget class="QPushButton" name="pushButton_top">
<property name="geometry">
<rect>
<x>120</x>
<y>60</y>
<width>93</width>
<height>28</height>
</rect>
</property>
<property name="text">
<string>PushButton</string>
</property>
</widget>
<widget class="QLabel" name="label_2">
<property name="geometry">
<rect>
<x>380</x>
<y>60</y>
<width>72</width>
<height>15</height>
</rect>
</property>
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</widget>
<resources/>
<connections/>
<buttongroups>
<buttongroup name="buttonGroup_2"/>
</buttongroups>
</ui>
二、在线程中更新时间或者进行耗时的操作,然后通过发送信号,通过主线程中的槽进行接收,并在主线程更新UI显示
import time
from threading import Thread
import datetime
from PyQt5 import uic
from PyQt5.QtCore import pyqtSignal, QObject
from PyQt5.QtWidgets import QApplication, QMessageBox, QTableWidgetItem, QWidget
import threading
class Stats(QWidget):
sendmsg_clock = pyqtSignal(str) # 定义时钟的信号
sendmsg_edit = pyqtSignal() # 定义另一个信号
def __init__(self):
super().__init__()
self.ui = uic.loadUi("ui/demo2.ui")
self.sendmsg_clock.connect(self.update_clock)
self.sendmsg_edit.connect(self.update_lab)
self.initUI()
def initUI(self):
self.ui.pushButton.clicked.connect(self.click)
self.ui.pushButton_top.clicked.connect(self.click_top)
def click_top(self):
t = threading.Thread(target=self.click_top_thread)
t.start()
def click_top_thread(self):
self.sendmsg_edit.emit()
# print(self.ui.lineEdit.text())
def click(self):
print('click')
t = threading.Thread(target=self.time_thread)
t.start()
def time_thread(self):
while True:
now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
self.sendmsg_clock.emit(now)
time.sleep(1)
def update_clock(self,_time):
# 定义时钟的槽
self.ui.label.setText(_time)
def update_lab(self):
# 更新edit的ui的槽
info = self.ui.lineEdit.text()
self.ui.label_2.setText(info)
if __name__ == '__main__':
app = QApplication([])
stats = Stats()
stats.ui.show()
app.exec_()