Pyqt5 中的 SetText

问题描述

我正在 pyqt5 中开发一个应用程序,但遇到了一个问题。 有一个接收数据的脚本,在pyqt5的“main_text.setText(str(TEXT))”行中我输出它们,格式为“str” 但是脚本本身每0.2s接收和输出数据,但是在“main_text.setText (str (TEXT))”行中,它们没有更新。 试过定时休眠功能,app不行,

pyqt5中有什么方法可以将不同的数据输出到同一个集合文本?

我的代码

from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication,QMainWindow

import sys
import MetaTrader5 as mt5

import time

mt5.initialize()

ticket_info = mt5.symbol_info_tick("EURUSD")._asdict()
bid_usd = mt5.symbol_info_tick("EURUSD").bid

def applecation():
    app = QApplication(sys.argv)
    window = QMainWindow()

    window.setwindowTitle('Test Programm')
    window.setGeometry(300,250,350,200)


    main_text = QtWidgets.QLabel(window)
    main_text.setText(str(bid_usd))
    main_text.move(100,100)
    main_text.adjustSize()

    window.show()

    sys.exit(app.exec_())

if __name__ == "__main__":
    applecation()

解决方法

您只调用了一次 symbol_info_tick 方法,因此您只会获取一个数据,如果您想每 T 秒获取一次该信息,那么您必须使用在辅助线程中执行的 while True 以便它不会阻塞GUI并通过信号发送信息。

import sys
import threading
import time

from PyQt5.QtCore import QObject,pyqtSignal
from PyQt5.QtWidgets import QApplication,QLabel,QMainWindow

import MetaTrader5 as mt5


class MetaTrader5Worker(QObject):
    dataChanged = pyqtSignal(str)

    def start(self):
        threading.Thread(target=self._execute,daemon=True).start()

    def _execute(self):
        mt5.initialize()
        while True:
            bid_usd = mt5.symbol_info_tick("EURUSD").bid
            self.dataChanged.emit(str(bid_usd))
            time.sleep(0.5)


class MainWindow(QMainWindow):
    def __init__(self,parent=None):
        super().__init__(parent)
        self.label = QLabel(self)
        self.setWindowTitle("Test Programm")
        self.setGeometry(300,250,350,200)

    def handle_data_changed(self,text):
        self.label.setText(text)
        self.label.adjustSize()


def main():
    app = QApplication(sys.argv)

    window = MainWindow()
    window.show()

    worker = MetaTrader5Worker()
    worker.dataChanged.connect(window.handle_data_changed)
    worker.start()

    sys.exit(app.exec_())


if __name__ == "__main__":
    main()