PySide: Easier way of updating GUI from another thread

I have a PySide (Qt) GUI which spawns multiple threads. The threads sometimes need to update the GUI. I have solved this in the following way:

class Signaller(QtCore.QObject) :
    my_signal = QtCore.Signal(QListWidgetItem, QIcon)
signaller = Signaller()

class MyThread(threading.Thread):
    def __init__(self):
        super(IconThread, self).__init__()
        # ...

    def run(self) :
        # ...

        # Need to update the GUI
        signaller.my_signal.emit(self.item, icon)

# MAIN WINDOW        
class Main(QtGui.QMainWindow):

    def __init__(self):

        # ...

        # Connect signals

    @QtCore.Slot(QListWidgetItem, QIcon)
    def my_handler(self, item, icon):

    def do_something(self, address):
        # ...

        # Start new thread 
        my_thread = MyThread(newItem)

    # ...

Is there an easier way? Creating the signals, handlers and connect them requires a few lines of code.


I started coding with PySide recently and I needed a equivalent of PyGObject's GLib.idle_add behaviour. I based the code off of your answer ( ) but this one uses events instead of using a queue ourselves.

from PySide import QtCore

class InvokeEvent(QtCore.QEvent):
    EVENT_TYPE = QtCore.QEvent.Type(QtCore.QEvent.registerEventType())

    def __init__(self, fn, *args, **kwargs):
        QtCore.QEvent.__init__(self, InvokeEvent.EVENT_TYPE)
        self.fn = fn
        self.args = args
        self.kwargs = kwargs

class Invoker(QtCore.QObject):
    def event(self, event):
        event.fn(*event.args, **event.kwargs)

        return True

_invoker = Invoker()

def invoke_in_main_thread(fn, *args, **kwargs):
        InvokeEvent(fn, *args, **kwargs))

Which is used the same way in the above answer link.

This is what I have so far. I wrote the following code somewhere in a helper module:

from Queue import Queue
class Invoker(QObject):
    def __init__(self):
        super(Invoker, self).__init__()
        self.queue = Queue()

    def invoke(self, func, *args):
        f = lambda: func(*args)
        QMetaObject.invokeMethod(self, "handler", QtCore.Qt.QueuedConnection)

    def handler(self):
        f = self.queue.get()
invoker = Invoker()

def invoke_in_main_thread(func, *args):

Then my threads can very easily run code to update the GUI in the main thread. There is no need to create and connect signals for every operation.

class MyThread(threading.Thread):
    def __init__(self):
        super(IconThread, self).__init__()
        # ...

    def run(self) :
        # ...

        # Need to update the GUI
        invoke_in_main_thread(self.item.setIcon, icon)

I think something like this is quite nice.

Need Your Help

Smooth mouse wheel scrolling

javascript css google-chrome scroll mousewheel

I use chrome and scrolling is fast but its dont smooth. Text jumps multiple times.