PyQt5系列文章
效果图
完整代码
import sys
import time
from PyQt5.QtCore import QThread, pyqtSignal, QDateTime
from PyQt5.QtWidgets import QPushButton,QHBoxLayout,QWidget,QApplication,QMainWindow
class QThreadDemo(QMainWindow):
def __init__(self):
super(QThreadDemo, self).__init__()
self.resize(400, 150)
self.setWindowTitle("QThreadDemo")
self.button1 = QPushButton("按钮一")
self.button1.clicked.connect(self.startThread)
self.myThread = myThread()
self.myThread.mySignal1.connect(self.handleSignal1)
layout = QHBoxLayout()
layout.addWidget(self.button1)
mainFrame = QWidget()
mainFrame.setLayout(layout)
self.setCentralWidget(mainFrame)
def startThread(self):
print(time.strftime("%H:%M:%S", time.localtime()) + "> button clicked!")
self.button1.setEnabled(False)
self.myThread.start()
def handleSignal1(self, str):
print(time.strftime("%H:%M:%S", time.localtime()) + "> recv mySignal1, value: " + str)
class myThread(QThread):
mySignal1 = pyqtSignal(str)
def __init__(self,*args, **kwargs):
super(myThread, self).__init__(*args, **kwargs)
def run(self, *args, **kwargs):
while True:
time.sleep(3)
print(time.strftime("%H:%M:%S", time.localtime()) + "> emit mySignal1")
self.mySignal1.emit('3')
if __name__ == '__main__':
app = QApplication(sys.argv)
main = QThreadDemo()
main.show()
sys.exit(app.exec_())