PyQt QThread:线程仍在运行时被销毁

Nyxynyx

尽管保存了对QThreadas的引用,但self.lightsThread停止QObject self.lightsWorker然后self.lightsThread再次启动仍导致错误

QThread: Destroyed while thread is still running

停止后self.lightsWorker,也必须QThread self.lightsThread停止吗?如果没有,似乎是什么问题?

import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import time



class Screen(QMainWindow):
    def __init__(self):
        super(Screen, self).__init__()
        self.initUI()

    def initUI(self):
        self.lightsBtn = QPushButton('Turn On')
        self.lightsBtn.setCheckable(True)  
        self.lightsBtn.setStyleSheet("QPushButton:checked {color: white; background-color: green;}")
        self.lightsBtn.clicked.connect(self.lightsBtnHandler)

        self.setCentralWidget(self.lightsBtn)

    def lightsBtnHandler(self):
        if self.lightsBtn.isChecked():
            self.startLightsThread()
        else:
            self.stopLightsThread()

    def startLightsThread(self):
        print 'start lightsThread'
        self.lightsThread = QThread()
        self.lightsWorker = LightsWorker()
        self.lightsWorker.moveToThread(self.lightsThread)
        self.lightsThread.started.connect(self.lightsWorker.work)
        self.lightsThread.start()


    def stopLightsThread(self):
        print 'stop lightsThread'
        self.lightsWorker.stop()



class LightsWorker(QObject):
    signalFinished = pyqtSignal()

    def __init__(self):
        QObject.__init__(self)
        self._mutex = QMutex()
        self._running = True

    @pyqtSlot()
    def work(self):
        while self._running:
            print 'working'
            time.sleep(1)
        self.signalFinished.emit()

    @pyqtSlot()
    def stop(self):
        print 'Stopping'
        self._mutex.lock()
        self._running = False
        self._mutex.unlock()



app = QApplication(sys.argv)
window = Screen()
window.show()
sys.exit(app.exec_())
卢奇科

停止后遵循答案https://stackoverflow.com/a/32138213/7742341lightWorker您应该退出线程并等待直到停止

def stopLightsThread(self):
    print('stop lightsThread')
    self.lightsWorker.stop()
    self.lightsThread.quit()
    self.lightsThread.wait()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

PyQt5-QThread:线程仍在运行时被销毁

PYQt5:QThread:线程仍在运行时销毁(实例分配为 QDialog )

PyQt5:线程仍在运行时被销毁

退出时“ QThread:线程仍在运行时被销毁”

QThread 在线程仍在运行时被销毁

PySide2 QThread错误:QThread:线程仍在运行时被销毁

从Windows cmd或IDLE而不是从PyCharm运行时出现“ QThread:线程仍在运行时销毁”的问题?

QThread:在线程仍在QTest中运行时销毁

QThread:线程仍在运行时被破坏了吗?

PyQt线程在窗口关闭后仍在运行

在运行时在 PyQt5 中添加 Qlabels

Qt:在关闭期间线程仍在运行时,qthread被破坏

PyQt-在运行时创建QLabel,然后更改文本

PyQt:在运行时将小部件添加到scrollarea

在运行时更改模型的根路径 - PyQt5

PySide:线程销毁后仍在运行

PyQt对话框在线程运行时不负责

QProcess:进程(Web浏览器)仍在运行时被销毁

Qt避免警告'QProcess:在进程仍在运行时销毁

在 PyQt5 中使用 QThread 运行多个后台线程

C#-在创建新控件的线程仍在运行时关闭表单

PyQt5:更新标签的运行时间

Pyqt5 qlabel 在按钮运行时更新

PyQt中带有QThread的后台线程

如何在主线程仍在运行时使用线程运行另一个 JFrame

PyQt5如果python仍在运行,则在使用评估JavaScript时如何更新GUI

在程序仍在运行时,如何查看nohup文件?

在进程仍在运行时旋转日志文件

嵌套函数仍在运行时暂停外部函数