小编Pra*_*ete的帖子

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

我是 PySide2 的新手。我只是想启动一个示例应用程序并在应用程序启动时启动一个线程,并希望在应用程序关闭时停止该线程。当我关闭应用程序时,我收到以下错误:QThread:线程仍在运行时已销毁。sample_ui.py 是我从 sample_ui.ui 转换而来的 python 文件

代码:

import time
import sys
import sample_ui
from PySide2 import QtWidgets
from PySide2 import QtCore


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        main_window_ui = sample_ui.Ui_MainWindow()
        main_window_ui.setupUi(self)
        self.custom_thread = CustomThread()
        self.custom_thread.start()

    def closeEvent(self, event):
        self.custom_thread.stop()
        QtWidgets.QMainWindow.closeEvent(self, event)

class CustomThread(QtCore.QThread):
    def __init__(self):
        super(CustomThread, self).__init__()
    def run(self):
        while self.isRunning():
           print("Thread is Running")
           time.sleep(1)
    def stop(self):
        print("Thread Stopped")
        self.quit()




if __name__ == '__main__':
    app = QtWidgets.QApplication()
    main_window = MainWindow()
    main_window.show()
    sys.exit(app.exec_())

Run Code Online (Sandbox Code Playgroud)

输出:

Thread is Running
Thread …
Run Code Online (Sandbox Code Playgroud)

qt pyqt pyqt5 pyside2

3
推荐指数
1
解决办法
786
查看次数

标签 统计

pyqt ×1

pyqt5 ×1

pyside2 ×1

qt ×1