Recherche…


Remarques

Bien que certaines parties du framework Qt soient sûres, la plupart ne le sont pas. La documentation Qt C ++ fournit un bon aperçu des classes réentrantes (peuvent être utilisées pour instancier des objets dans plusieurs threads). Les règles suivantes sont les plus recherchées:

  • Vous ne pouvez pas créer ou accéder à un objet graphique Qt en dehors du thread principal (par exemple, tout ce qui sous-classe QWidget ou similaire).
  • Même si la classe Qt est réentrante, vous ne pouvez pas partager l'accès à un objet Qt entre les threads, sauf si la documentation Qt de cette classe indique explicitement que les instances sont sûres pour les threads.
  • Vous pouvez utiliser QObject.moveToThread() si vous devez déplacer un objet Qt d'un thread vers un autre (ne s'applique pas aux objets d'interface graphique Qt qui doivent toujours rester dans le thread principal). Mais notez que l'objet ne doit pas avoir de parent.

Selon ce QA de Stack Overflow, il n'est pas recommandé d'utiliser les threads Python si votre thread a l'intention d'interagir avec PyQt de quelque manière que ce soit (même si cette partie du framework Qt est thread-safe).

Le modèle de travailleur

# 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
Sous licence CC BY-SA 3.0
Non affilié à Stack Overflow