Tur*_*ute 1 python qt multithreading python-3.x pyqt5
我正在使用PyQt和Python3.
我QTimer没有调用他们被告知连接的功能.isActive()正在返回True,并interval()正在正常工作.下面的代码(单独工作)演示了问题:线程已成功启动,但timer_func()从未调用该函数.大多数代码都是样板PyQT.据我所知,我正在按照文档使用它.它在一个带有事件循环的线程中.有任何想法吗?
import sys
from PyQt5 import QtCore, QtWidgets
class Thread(QtCore.QThread):
def __init__(self):
QtCore.QThread.__init__(self)
def run(self):
thread_func()
def thread_func():
print("Thread works")
timer = QtCore.QTimer()
timer.timeout.connect(timer_func)
timer.start(1000)
print(timer.remainingTime())
print(timer.isActive())
def timer_func():
print("Timer works")
app = QtWidgets.QApplication(sys.argv)
thread_instance = Thread()
thread_instance.start()
thread_instance.exec_()
sys.exit(app.exec_())
Run Code Online (Sandbox Code Playgroud)
你使用线程thread_func的run方法调用,这意味着你在该函数中创建的计时器存在于该线程的事件循环中.要启动一个线程事件循环,则必须调用它的exec_()方法,从内它的run方法,而不是从主thrad.在你的例子中,app.exec_()永远不会被执行.要使它工作,只需将exec_调用移动到线程中即可run.
另一个问题是,当thread_func完成时,你的计时器会被销毁.为了保持活着,你必须在某个地方保留一个参考.
import sys
from PyQt5 import QtCore, QtWidgets
class Thread(QtCore.QThread):
def __init__(self):
QtCore.QThread.__init__(self)
def run(self):
thread_func()
self.exec_()
timers = []
def thread_func():
print("Thread works")
timer = QtCore.QTimer()
timer.timeout.connect(timer_func)
timer.start(1000)
print(timer.remainingTime())
print(timer.isActive())
timers.append(timer)
def timer_func():
print("Timer works")
app = QtWidgets.QApplication(sys.argv)
thread_instance = Thread()
thread_instance.start()
sys.exit(app.exec_())
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6254 次 |
| 最近记录: |