Use self object of a class in a thread class

Hi all,
I’m writing a pyqt code and I defined many functions in the main class which load the UI. To avoid freezing phenomena I added some Qthreads and inside them I would like change UI interfaces (example: labels, color of button etc) and use functions defined in the main class which call the threads.

example:


class threadClass(Object):
   def run(self):
        ....
        *self.runFunc()*

class Ui(QMainWindow):
   def __init__(self):
        super().__init__()
        ....
        self.thread = QThread()
        self.worker = threadClass(self)
        self.worker.moveToThread(self.thread)
        self.thread.started.connect(self.worker.run)
   
   def funct(self):
        ...

there is a solution?

As written, your Ui instance will be passing its own self value to your threadClass instance.
But you need an __init__method in threadClass to store it somewhere, something like:

[code/]
def init_(self, parent):
self.parent =parent
/code/]

But the last two lines show that you don’t need to do this; you can just pass a reference value of an attribute of the Ui instance to the worker or Qt thread when you need to.

By attribute I mean any variable or method.

Finally your syntax for the run method is wrong, this is not C.
self.runfunc() would work if you have previously stored it,
for example:

def __init__(self, runfunc):
    self.runfunc = runfunc

tahnk you very much for your reply.

I have one more question.

I tried to apply your suggestions but I don’t understant something:

class threadClass(Object):
   def __init__():
        self.parent = parent
   def run(self):
        ....
        self.parent.runFunc()

the code runs with the error

RuntimeError: super-class __init__() of type writeCSVIteration was never called

so I added
super().init(parent) in the def init function but the following error appears and the code don’t procede with the main projects as espected because the thread have to run in a parallel way.

QObject::moveToThread: Cannot move objects with a parent

Do you have some suggestions?