Apr-08-2019, 07:26 AM
(Apr-04-2019, 07:20 PM)Alfalfa Wrote: You should use another thread that make a request every second or so, and emit a signal to update the value of your GUI.
#!/usr/bin/python3 # Threading example with QThread and moveToThread (PyQt5) import sys import time from PyQt5 import QtWidgets, QtCore class WorkerThread(QtCore.QObject): signalExample = QtCore.pyqtSignal(str, int) def __init__(self): super().__init__() @QtCore.pyqtSlot() def run(self): while True: # Long running task ... self.signalExample.emit("leet", 1337) time.sleep(5) class Main(QtWidgets.QMainWindow): def __init__(self): super().__init__() self.worker = WorkerThread() self.workerThread = QtCore.QThread() self.workerThread.started.connect(self.worker.run) # Init worker run() at startup (optional) self.worker.signalExample.connect(self.signalExample) # Connect your signals/slots self.worker.moveToThread(self.workerThread) # Move the Worker object to the Thread object self.workerThread.start() def signalExample(self, text, number): print(text) print(number) if __name__== '__main__': app = QtWidgets.QApplication([]) gui = Main() sys.exit(app.exec_())
First of al, I tried this. I added socket function, HOST adress, PORT number and some rows for client. My output should be distance "data".
self.signalExample.emit("distance", data) . . . def signalExample(self, text, data): print(text) print(data)But instead of data, there are many different large numbers in gui widget. I cant reach data on IP.
Maybe I must share all of them for you.
import sys import time import socket from PyQt5 import QtWidgets, QtCore HOST = '192.168.1.33' # The server's hostname or IP address PORT = 80 # The port used by the server with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((HOST, PORT)) s.sendall(b'Hello, world') data = s.recv(1024) print(data) class WorkerThread(QtCore.QObject): signalExample = QtCore.pyqtSignal(str, int) def __init__(self): super().__init__() @QtCore.pyqtSlot() def run(self): while True: # Long running task ... self.signalExample.emit("distance", data) time.sleep(5) class Main(QtWidgets.QMainWindow): def __init__(self): super().__init__() self.worker = WorkerThread() self.workerThread = QtCore.QThread() self.workerThread.started.connect(self.worker.run) # Init worker run() at startup (optional) self.worker.signalExample.connect(self.signalExample) # Connect your signals/slots self.worker.moveToThread(self.workerThread) # Move the Worker object to the Thread object self.workerThread.start() def signalExample(self, text, data): print(text) print(data) if __name__== '__main__': app = QtWidgets.QApplication([]) gui = Main() sys.exit(app.exec_())
Output:PS C:\Users\User> & "C:/Program Files/Python37/python.exe" c:/Users/User/Desktop/PYQT/time_socket.py
b'52'
distance
1895228464
distance
1895228464
For example, 52 cm is right but i cant understand what is other big number.