1
我想了解QT5線程的基礎知識。這是我第一次嘗試,結合各種來源:PyQt5 QThread問題
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)
我已經在代碼片段中包含了錯誤。 從在線文章中我瞭解到,在PyQt5中,我不應該繼承QThread。
OMG這樣愚蠢的錯誤,簡直不敢相信。非常感謝 – Anonimista