我想做的是从 GUI 创建一个单独的线程,然后在循环中每 0.01 秒更新一次 GUI 文本。我通过搜索网络想出了以下代码,但应用程序似乎卡在 while 循环中。
count()
不是应该在另一个线程中运行吗?怎么了?
import sys
import time
from PySide6.QtCore import QSize, Qt, QThreadPool, Slot
from PySide6.QtWidgets import QApplication, QMainWindow, QPushButton
class MainWindow(QMainWindow):
Count = 1;
def __init__(self):
super().__init__()
self.setWindowTitle("My App")
self.MyButton = QPushButton()
self.setCentralWidget(self.MyButton)
self.threadManager = QThreadPool();
def showEvent(self, event):
self.threadManager.start(self.count())
@Slot()
def count(self):
while(True):
self.Count+=1;
self.refreshButtonText();
time.sleep(0.01)
def refreshButtonText(self):
self.MyButton.setText(f"Count {self.Count}")
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()
您不小心调用了
count
而不是将其作为函数传递。
self.threadManager.start(self.count)
考虑使用信号槽机制发送数据消息,而不是直接访问另一个线程中的对象。
您可以轻松找出某个线程在哪个线程中运行
print("I'm running in", QThread.currentThread())
您可以使用计时器代替线程
import sys
from PySide6.QtCore import QTimer
from PySide6.QtWidgets import QApplication, QMainWindow, QPushButton
class MainWindow(QMainWindow):
Count = 1
def __init__(self):
super().__init__()
self.setWindowTitle("My App")
self.MyButton = QPushButton()
self.setCentralWidget(self.MyButton)
def showEvent(self, event):
timer = QTimer(self)
timer.timeout.connect(self.count)
timer.start(10)
def count(self):
self.Count+=1
self.refreshButtonText()
def refreshButtonText(self):
self.MyButton.setText(f"Count {self.Count}")
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()