0

I am trying to run a process in a different thread using PyQt5 to not block the UI-thread (Main thread).

I made a Child class of the QtCore.QRunnable and QObject classes to pass my function to the threadpool and would like to get the result of the run function by using a signal. Inside my main UI i create the worker and connect it to a callback, then start the worker. The fn does nothing in this example, and the callback only prints the value. When i run this code, it crashes with following message:
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)

What am i doing wrong, and how can i connect to the worker to receive the return value of my function without crashing the code or UI? I've only found this post on the topic, but it is only about QThreads and not QRunnable, which functions differently afaik.

from PyQt5.QtWidgets import  QMainWindow, QApplication
from PyQt5 import QtCore
import sys

class Worker(QtCore.QRunnable, QtCore.QObject):
    trigger = QtCore.pyqtSignal(int)

    def __init__(self, function, *args, **kwargs):
        super().__init__()
        self.function = function
        self.args = args
        self.kwargs = kwargs

    @QtCore.pyqtSlot()
    def run(self):
        self.function(*self.args, **self.kwargs)
        self.trigger.emit(1)


class Window(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Title")
        self.threadpool = QtCore.QThreadPool()
        self.show()
        self.run_fn()

    def test_fn(self, i=0):
        return i

    @QtCore.pyqtSlot()
    def test_callback(self, i):
        print(i)

    def run_fn(self):
        worker = Worker(self.test_fn, 1)
        worker.trigger.connect(self.test_callback)
        self.threadpool.start(worker)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Window()
    sys.exit(app.exec_())
fogx
  • 1,749
  • 2
  • 16
  • 38
  • sure... I reformatted the question. – fogx Jan 21 '20 at 17:21
  • thank you for the links @eyllanesc. can you explain why the code threw a SIGSEGV though? I did not connect the multiple inheritance issue with that error and did not get that far. – fogx Jan 21 '20 at 18:08
  • 1
    PyQt has many limitations, and among them that there cannot be multiple inherent between QObject and QRunnable (there are only certain cases in which pyqt allows them), so therefore even if you want to do it some things do not end up being built (it is not reserved memory for certain very important variables) but you try to use some of its methods to access unallocated memory causing that well-known error. – eyllanesc Jan 21 '20 at 18:12

0 Answers0