首页 > 解决方案 > Python QThread 与主程序的通信

问题描述

我需要在主程序(QMainWindow)的文本区域中显示来自线程的一些信息,但我找不到正确的说明来执行此操作

我使用一个线程来避免用另一个函数中的循环来冻结主程序。

该线程在执行期间显示了一些信息,但我不明白如何将变量传递给主程序(QMain)并显示。

我在这里写下我的代码。

你有什么建议可以帮助我吗?

谢谢里斯托夫

import sys
from PySide6.QtCore import *
from PySide6.QtGui import *
from PySide6.QtWidgets import *
import time

class MainWindow(QMainWindow):

    process = 0

    def __init__(self):
        super().__init__()
        self.setup()

    def setup(self):
        QtWidgets = QWidget(self)

        # traitement de la fenetre principale
        self.setGeometry(200, 200, 400, 400)  # dimension de la fenetre
        self.setWindowTitle('AOT Automate v2')

        # Traitement des actions
        startAction = QAction(QIcon("exit.png"), "&Start / Stop", self)
        startAction.setShortcut("Ctrl+S")
        startAction.setStatusTip("Lancer les processus")
        startAction.triggered.connect(self.Menu_Start)

        exitAction = QAction(QIcon("exit.png"), "&Exit", self)
        exitAction.setShortcut("Ctrl+Q")
        exitAction.setStatusTip("Quitter l'application")
        exitAction.triggered.connect(qApp.quit)

        # creation des menus
        ExitMenu = self.menuBar().addMenu("&Menu");
        ExitMenu.addAction(startAction);
        ExitMenu.addAction(exitAction);

        self.textBrowser = QTextBrowser()
        self.textBrowser.setStyleSheet('font-size: 12px')
        self.setCentralWidget(self.textBrowser)
        #self.textBrowser.moveCursor(QTextCursor.Start)
        self.textBrowser.append("Message from the tread must be displayed in this field")
     
        self.worker = WorkerThread()

        # Barre outil du bas
        self.statusBar().showMessage("Ready",2000)
        self.show()

    def Menu_Start(self):

        if self.process == 0:
            print("entre")
            self.worker.start()
            self.process = 1
        else:
            print("exit")
            self.worker.terminate()
            self.process = 0

class WorkerThread(QThread):

    def run(self):
        i = 2
        while i != 0:
            print("loop of messages from the tread must be displayed in the MainProgram")
           
def run():

    app = QApplication(sys.argv)
    ex = MainWindow()
   app.exec_()

if __name__ == '__main__':
    run()

标签: pythonmultithreadingsignalscommunicationqthread

解决方案


推荐阅读