Search code examples
pythonpyqtpyqt5metatrader5

SetText in Pyqt5


I am developing an application in pyqt5 and I ran into one problem. There is a script that receives data, and in pyqt5 in the line "main_text.setText (str (TEXT))" I output them, and in the format "str" ​ But the script itself receives and outputs data every 0.2s, but in the line "main_text.setText (str (TEXT))" they are not updated. Tried through the time sleep function, the app doesn't work,

what method in pyqt5 can be used to output different data to the same set text ?

My code :

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

Solution

  • You are invoking the symbol_info_tick method only once so you will only get a data, if you want to get that information every T seconds then you must use a while True that is executed in a secondary thread so that it does not block the GUI and send the information through of signals.

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