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()

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)