QtConcurrent in PySide/PyQt

Question:

I’m trying to figure out if subclassing QtConcurrent and writing a run method inside it will work:

class Task(QtCore.QtConcurrent):

     def run(self, function):
           function()

Or is it completely useless?

Asked By: Elteroooo

||

Answers:

It’s completely useless, because QtConcurrent is a namespace, not a class.

Also, neither PyQt nor PySide provide any of the functionality provided by QtConcurrent, because it’s all template-based and therefore impossible to wrap.

PS: the PySide documentation you linked to is for the ReduceOption enum. Since it’s doubtful whether that enum has any use outside the QtConcurrent namespace, it’s probably a bug that PySide includes it.

Answered By: ekhumoro

The class you are looking for is QRunnable.

Answered By: Grumbel

I am stuck on the same problem in PyQt5. I guess the only solution is to do this locally:

def connect(self):
    class ConnectThread(QThread):
        def __init__(self, func):
            super().__init__()
            self.func = func
        def run(self):
            self.func()
    self.connectThread = ConnectThread(self._connect)
    self.connectThread.start()

def _connect(self):
    if self._driver is None:
        uri = self.uriString()
        if uri and self.user and self.password:
            self.statusMessage.emit("Connecting to the Graph Database....", -1, "color:blue;")
            try:
                self._driver = GraphDatabase.driver(uri, auth=(self.user, self.password))
                self.statusMessage.emit("Connected!", 5000, "color:green;")
            except Exception as e:
                self.clearStatusMessage.emit()
                Error(str(e)).exec_()
                if __debug__:
                    raise e

And remember to set the thread to a member variable: self.thread = ... or else your thread reference will go out of scope, and most likely the thread object deleted.

You could also move your function-to-call into a local definition of it as Python allows both nested functions and classes within one another!

Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.