Skip to content Skip to sidebar Skip to footer

Pyside2 Qthread Crash

I want to use PySide2 Qtcore.Qthread because of Qtcore.Signal, but I end up with this error: Process finished with exit code -1073740791 from PySide2.QtCore import QThread class

Solution 1:

Explanation

If you run your code in a CMD/Terminal you will get the following error:

QThread: Destroyed while thread is still running
Aborted (core dumped)

And the error is caused because the thread is destroyed while it is still running since it is a local variable, on the other hand QThread needs an event loop to run

Solution

import sys
from PySide2.QtCore import QCoreApplication, QThread


classThread(QThread):
    defrun(self):
        print("task started")
        k = 0for i inrange(10000):
            for j inrange(5000):
                k += 1print("task finished")


if __name__ == "__main__":
    # create event loop
    app = QCoreApplication(sys.argv)

    th = Thread()
    th.start()

    th.finished.connect(QCoreApplication.quit)
    sys.exit(app.exec_())

Update:

"t" is a local variable that will be eliminated after executing clicked causing the same problem as your initial code, the solution is to prevent it from being destroyed instantly and for this there are 2 options:

  • Make a "t" class attribute
defclicked(self):
    self.t = Thread()
    self.t.done.connect(self.done)
    self.t.start()
  • Store the QThread in a container that has a longer life cycle:
classWidget(QtWidgets.QWidget):def__init__(self):
        super(Widget, self).__init__()
        btn = QtWidgets.QPushButton('test', parent=self)
        btn.clicked.connect(self.clicked)

        self.container = []

    defclicked(self):
        t = Thread()
        t.done.connect(self.done)
        t.start()
        self.container.append(t)

    # ...
  • Pass it as a parent to "self" but for this it is necessary that Thread allow to receive so you must implement that in the constructor:
classThread(QThread):
    done = Signal()

    def__init__(self, parent=None):
        super(Thread, self).__init__(parent)

    # ...
defclicked(self):
    t = Thread(self)
    t.done.connect(self.done)
    t.start()

Solution 2:

I found the solution but I don't know why I should do this. the thread should a part of the class.

self.t = Thread()
self.t.done.connect(self.done)
self.t.start()

Post a Comment for "Pyside2 Qthread Crash"