Passing an argument when starting new QThread() in PyQt

后端 未结 2 552
不知归路
不知归路 2021-01-01 04:29

I have a multi-threaded application written in Python in which one thread \"takes care\" of the GUI, and the other is the worker thread. However, the worker thread has two m

相关标签:
2条回答
  • 2021-01-01 05:05

    Eli Bendersky's answer is correct, however the order of arguments appears wrong.

    If you call the Worker class like this:

    The argument order that worked for me:

    def __init__(self, parent=None, do_create_data=True):  
    

    The order shown in Eli Bendersky's answer produced this error message for me:

    TypeError: QThread(QObject parent=None): argument 1 has unexpected type 'str'
    

    Not sure why, but I'm sure someone can help explain.

    0 讨论(0)
  • 2021-01-01 05:06

    The start method of QThread doesn't accept arguments. However, you've inherited QThread so you're free to customize it at will. So, to implement what you want, just pass arguments into the constructor of Worker.

    Here's your code sample slightly modified to show this in action:

    class Worker(QThread):
      def __init__(self, do_create_data=True, parent=None):
        super(QThread, self).__init__()
        self.do_create_data = create_data
    
      def run(self):
         if self.create_data:
             self.create_data()
         else:
             self.upload_data(), depends
    
    0 讨论(0)
提交回复
热议问题