【发布时间】:2018-06-10 17:29:52
【问题描述】:
我必须说这是一个初学者的问题。但是我尝试/搜索了很多但没有成功。
有一个QLabel,通过运行我希望将子线程中的值显示在上面的代码。
我也想在子线程中有QTimer,因为时间是在那里控制的(不是在主线程QThread)。
这是我想要实现的QLable上的效果...
0 (show for 1 second)
1 (show for 1 second)
2 (show for 1 second)
...
11 (show for 2 second)
12 (show for 2 second)
...
21 (show for 3 second)
22 (show for 3 second)
...
这是我的代码:
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class WorkerThread(QThread):
def __init__(self, parent=None):
super(WorkerThread, self).__init__(parent)
self._running = False
self.timer = QTimer() # Question: define the QTimer here?
self.timer.timeout.connect(self.doWork)
self.timer.start(1000)
def run(self):
self._running = True
while self._running:
self.doWork()
def doWork(self):
for i in range(40): # Question: How to return the i onto the QLable?
if i <= 10:
# show the value of i on the QLabel and wait for 1 second
pass
elif i <= 20:
# show the value of i on the QLable and wait for 2 second
pass
elif i <= 30:
# show the value of i on the QLable and wait for 3 second
pass
else:
# show the value of i on the QLable and wait for 4 second
pass
def stop(self, wait = False):
self._running = False
if wait:
self.wait()
class MyApp(QWidget):
def __init__(self, parent= None):
super(MyApp, self).__init__(parent)
self.thread = WorkerThread()
self.initUI()
def initUI(self):
self.text = "hello world"
self.setGeometry(100, 100, 500, 100)
self.setWindowTitle('test')
self.lbl_1 = QLabel("for every number between 0-10 wait 1 second, for 11-20 wait 2 sec, ...", self)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MyApp()
window.show()
sys.exit(app.exec_())
总结起来有两个问题:
1、如何在子线程中定义QTimer?
2. 如何将子线程的值返回给QLabel?
感谢您的帮助!
【问题讨论】:
标签: python pyqt pyqt5 qthread qtimer