How to pass parameters into QRunnable for pyqt5?

2019-08-18 06:08发布

问题:

I am able to pass functions to QRunnable however I am unable to pass function parameters along with them.

For example on line 19, it will except

worker = Worker(self.bitfinex) # parameters removed

But will raise the below error when I pass parameters

worker = Worker(self.bitfinex(self.ping))

full error message

Traceback (most recent call last):
  File "C:\Users\carl-\Documents\GitHub\DTL-Template\threads.py", line 37, in run
    self.fn(*self.args, **self.kwargs)
TypeError: 'NoneType' object is not callable

Really looking for an answer that will allow me to keep things as they are if possible but in away which will allow me to pass parameters directly into my worker function if that is possible of course?

import sys

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

import time
import traceback, sys


class MainWindow(QDialog):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        self.threadpool = QThreadPool()

        self.ping = 'value'

        button = QPushButton(self)
        button.setText('call worker')
        button.pressed.connect(self.api)

        self.show()

    def api(self):
        # error!
        # it will except self.bitfinex with no parameters
        # however if I add parameters I get the error
        worker = Worker(self.bitfinex(self.ping))
        self.threadpool.start(worker)

def bitfinex(self, ping):
    print(ping)


app = QApplication([])
window = MainWindow()
app.exec_()

Worker

class Worker(QRunnable):

def __init__(self, fn, *args, **kwargs):
    super(Worker, self).__init__()
    # Store constructor arguments (re-used for processing)
    self.fn = fn
    self.args = args
    self.kwargs = kwargs

@pyqtSlot()
def run(self):

    self.fn(*self.args, **self.kwargs)

Thanks