Using QThreadPool with QRunnable in PyQt4

2020-04-16 05:05发布

Consider the following code snippet

class Worker(QtCore.QRunnable):
    def __init__(self):
        super(Worker, self).__init__()

    def run(self):
        print('Running Worker')

class Tasks(QtCore.QObject):
    def __init__(self):
        super(Tasks, self).__init__()
        self.pool = QtCore.QThreadPool.globalInstance()
        self.pool.setMaxThreadCount(2)

    def start(self):
        for task in range(3):
            worker = Worker()
            self.pool.start(worker)
        self.pool.waitForDone()

def main():
    prefix_path = os.environ['QGIS_PREFIX_PATH']
    QgsApplication.setPrefixPath(prefix_path, True)
    QgsApplication.initQgis()
    tasks = Tasks()
    tasks.start()

i am getting the following error

_original_runnable_init(self, *args, **kwargs)
TypeError: keyword arguments are not supported

What is wrong with Worker Object creation?

1条回答
手持菜刀,她持情操
2楼-- · 2020-04-16 05:48

Don't know what is wrong with the QGis initialization, but the following code works as expected in my machine:

from PyQt4 import QtCore

class Worker(QtCore.QRunnable):
    def __init__(self):
        super(Worker, self).__init__()

    def run(self):
        print('Running Worker')

class Tasks(QtCore.QObject):
    def __init__(self):
        super(Tasks, self).__init__()
        self.pool = QtCore.QThreadPool.globalInstance()
        self.pool.setMaxThreadCount(2)

    def start(self):
        for task in range(3):
            worker = Worker()
            self.pool.start(worker)
        self.pool.waitForDone()

if __name__ == '__main__':
    tasks = Tasks()
    tasks.start()

It gives me the following output:

Running Worker
Running Worker
Running Worker
查看更多
登录 后发表回答