![](/img/trans.png)
[英]PyQt QTimer problem QTimer can only be used with threads started with QThread
[英]QThread can not be called in PyQt
我已經實現了有關QThread的子類,但是無法調用運行:
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class MyThread(QThread):
def __init__(self):
super(MyThread,self).__init__()
def run(self):
for i in range(1000):
print(i)
if __name__ == '__main__':
import sys
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.resize(500,500)
self.label = QLabel()
self.setCentralWidget(self.label)
layout = QHBoxLayout()
self.label.setLayout(layout)
btn = QPushButton('start')
layout.addWidget(btn)
btn.clicked.connect(self.BTNClick)
def BTNClick(self):
thread = MyThread()
thread.start()
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
當我調試代碼時,我發現MyThread正常運行。 但是當我直接運行代碼時,不會調用函數“ run”。
完成函數執行后,將刪除局部變量,在這種情況下,線程是BTNClick
的局部變量,因此在啟動時將其刪除,如果希望線程在執行BTNClick
之后仍然存在,則必須使用self
:
def BTNClick(self):
self.thread = MyThread()
self.thread.start()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.