Ricerca…


Osservazioni

Mentre alcune parti del framework Qt sono thread-safe, molte non lo sono. La documentazione di Qt C ++ offre una buona panoramica su quali classi sono rientranti (può essere usata per istanziare oggetti in più thread). Le seguenti regole sono le più ricercate:

  • Non è possibile creare o accedere a un oggetto Qt GUI al di fuori del thread principale (ad esempio, qualsiasi sottoclasse di QWidget o simili).
  • Anche se la classe Qt è rientranti, non è possibile condividere l'accesso a un oggetto Qt tra i thread a meno che la documentazione Qt per quella classe non specifichi esplicitamente che le istanze sono thread-safe.
  • È possibile utilizzare QObject.moveToThread() se è necessario spostare un oggetto Qt da un thread a un altro (non si applica agli oggetti Qt della GUI che devono sempre rimanere nel thread principale). Ma nota che l'oggetto non deve avere un genitore.

Come per questo QA di Overflow dello stack, non è consigliabile utilizzare i thread Python se il thread intende interagire con PyQt in qualsiasi modo (anche se quella parte del framework Qt è thread-safe).

Il modello di lavoratore

# this method can be anything and anywhere as long as it is accessible for connection
@pyqtSlot()
def run_on_complete():
   
    pass

# An object containing methods you want to run in a thread
class Worker(QObject):
    complete = pyqtSignal()
    
    @pyqtSlot()
    def a_method_to_run_in_the_thread(self):
        # your code
        
        # Emit the complete signal
        self.complete.emit() 

# instantiate a QThread
thread = QThread()
# Instantiate the worker object
worker = Worker()
# Relocate the Worker object to the thread
worker.moveToThread(thread)
# Connect the 'started' signal of the QThread to the method you wish to run
thread.started.connect(worker.a_method_to_run_in_the_thread)
# connect to the 'complete' signal which the code in the Worker object emits at the end of the method you are running
worker.complete.connect(run_on_complete)
# start the thread (Which will emit the 'started' signal you have previously connected to)
thread.start()


Modified text is an extract of the original Stack Overflow Documentation
Autorizzato sotto CC BY-SA 3.0
Non affiliato con Stack Overflow