Search code examples
pythonmultithreadingpyside

PySide2 signal not catched between threads with objects


I'm working on a GUI application, developed in Python and its UI library : PySide2 (Qt wrapper for Python)

I have a heavy computation function I want to put on another thread in order to not freeze my UI. The Ui should show "Loading" and when the function is over, receive from it it's results and update the UI with it.

I've tried a lot of different codes, a lot of examples are working for others but not me, is it PySide2 fault ? (For example this is almost what I want to do : Updating GUI elements in MultiThreaded PyQT)

My code is :

class OtherThread(QThread):

    def __init__(self):
        QThread.__init__(self)

    def run(self):
        print 'Running......'
        self.emit(SIGNAL("over(object)"), [(1,2,3), (2,3,4)])

@Slot(object)
def printHey( obj):
    print 'Hey, I\'ve got an object ',
    print obj

thr = OtherThread()
self.connect(thr,SIGNAL("over(object)"),printHey)
thr.start()

My code is working if I use primitives such as bool or int but not with object. I see 'Running....' but never the rest.

Hope someone can enlighten me


Solution

  • You can't define signals dynamically on a class instance. They have to be defined as class attributes. You should be using the new-style signals and slot syntax.

    class OtherThread(QThread):
        over = QtCore.Signal(object)
    
        def run(self):
            ...
            self.over.emit([(1,2,3), (2,3,4)])
    
    
    class MyApp(QtCore.QObject)
    
        def __init__(self):
            super(MyApp, self).__init__()
            self.thread = OtherThread(self)
            self.thread.over.connect(self.on_over)
            self.thread.start()
    
        @QtCore.Slot(object)
        def on_over(self, value):
            print 'Thread Value', value