简体   繁体   中英

pyqt4 qthread crashes python

Here is my code, which I created by copying various tutorials and SO posts:

import sys

from PyQt4.QtGui import *
from PyQt4.QtCore import QObject, pyqtSignal, QThread

class Worker(QThread):
    def __init__(self):

        QThread.__init__(self)

class MainWindow(QWidget):

    def __init__(self):
        super().__init__()

        worker = Worker()
        worker.start()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.resize(640, 480)
    window.show()
    sys.exit(app.exec_())

This is pretty simple, but when I run it python crashes immediately. I'm using Anaconda3 and I'm pretty darn sure that the python environment is all set up correctly, but I could be wrong. I am on Windows 10, 64-bit, Anaconda3 with Python 3.5 (64-bit). I installed qt4 using conda.

Your code is crashing because the worker thread is being destroyed while running. This happens because it is being created as a local variable within the constructor of MainWindow . After __init__() completes and worker falls out of scope it is subject to being removed by Python's garbage collector. In order to avoid this happening you can assign worker as a member of the Mainwindow class.

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.worker = Worker()
        self.worker.start()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM