【发布时间】:2017-11-30 12:22:55
【问题描述】:
我正在尝试了解 QT5 线程的基础知识。这是我的第一次尝试,结合了各种来源:
import sys
from time import sleep
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QGridLayout
from PyQt5.QtCore import QThread, QObject
'''
Traceback (most recent call last):
File "threads.py", line 68, in <module>
main(sys.argv)
File "threads.py", line 63, in main
window = Window()
File "threads.py", line 15, in __init__
self.initUi()
File "threads.py", line 28, in initUi
self.worker.moveToThread(self.thread)
AttributeError: 'NoneType' object has no attribute 'moveToThread'
Press any key to continue . . .
'''
class Window(QWidget):
def __init__(self):
super().__init__()
self.initUi()
self.low = 0
self.high = 100
self.show()
def initUi(self):
self.thread = QThread()
self.worker = Worker(self)
self.worker.moveToThread(self.thread)
self.thread.start()
self.button = QPushButton(
'Start long running task')
self.layout = QGridLayout()
self.layout.addWidget(self.button, 0, 0)
self.setLayout(self.layout)
def Worker(QObject):
def __init__(self, parent):
super(Worker, self).__init__(parent)
do_work()
def do_work(self):
for _ in range(20):
print('running . . .')
sleep(2)
def main(args):
app = QApplication(args)
window = Window()
sys.exit(app.exec_())
if __name__ == '__main__':
main(sys.argv)
我在代码 sn-p 中包含了我遇到的错误。 从在线文章中我了解到,在 PyQt5 中我不应该继承 QThread。
【问题讨论】:
标签: python pyqt pyqt5 python-multithreading