Implementation of PyQT display in Multithreaded Python program [duplicate] - python-3.x

This question already has answers here:
Background thread with QThread in PyQt
(7 answers)
Example of the right way to use QThread in PyQt?
(3 answers)
In PyQt, what is the best way to share data between the main window and a thread
(1 answer)
Closed 17 hours ago.
I am testing PyQT display window in multithread python program.
The PyQT display window doesn't display well.
PyQT display is as follow
But when the program runs, the display stops at the following stage
I see full display only when CTRL+C is pressed.
How to improve the program?
The whole code is here
import threading
import time
from threading import Thread
from threading import Event
import signal, os
import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, QGridLayout, QLabel)
class CameraStreamingWidget():
def __init__(self, ID):
self.id = ID
self.ready_lock = threading.Lock()
self.ready = False
self.stop_event = Event()
self.get_frame_thread = Thread(target=self.get_frame, args=())
self.get_frame_thread.daemon = True
self.get_frame_thread.start()
self.count = 0
self.before_read = time.time()
print("Camera "+str(ID)+" launched ");
def reset_ready_flag(self):
with self.ready_lock:
self.ready = False
return
def read_ready_flag(self):
ret = False
with self.ready_lock:
ret = self.ready
return ret
def get_frame(self):
while not self.stop_event.is_set():
try:
time.sleep(1)
self.count = self.count + 1
if(self.count >= 4):
cur_time = time.time()
print(f'cam_id {self.id}: {1000*(cur_time - self.before_read):.0f} ms')
with self.ready_lock:
self.ready = True
self.before_read = time.time()
self.count = 0
except AttributeError:
pass
class SIGINT_handler():
def __init__(self):
self.SIGINT_WORKER = False
def signal_handler(self, signal, frame):
print('\nYou pressed Ctrl+C!')
self.SIGINT_WORKER = True
handler = SIGINT_handler()
signal.signal(signal.SIGINT, handler.signal_handler)
class InferenceWidget():
def __init__(self,):
# source params
self.Cameras = []
for id_ in range(4):
cam = CameraStreamingWidget(id_)
self.Cameras.append(cam)
self.stop_event = Event()
self.runinference_thread = Thread(target=self.runinference, args=())
self.runinference_thread.daemon = True
self.runinference_thread.start()
def runinference(self):
#Run
while not self.stop_event.is_set():
#This is for detection
for id_,cam in enumerate(self.Cameras):
if cam.read_ready_flag() == True:
inference_start = time.time()
time.sleep(0.08)
cam.reset_ready_flag()
print(f'Inference time {1000*(time.time() - inference_start):.0f} ms for cam_id {id_}')
if handler.SIGINT_WORKER:
self.stopexecution()
return
def stopexecution(self):
print("Cameras are closed")
self.stop_event.set()
#python spatiotemporal_det_multicam.py
#Display images
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
grid = QGridLayout()
self.setLayout(grid)
names = ['Cls', 'Bck', '', 'Close',
'7', '8', '9', '/',
'4', '5', '6', '*',
'1', '2', '3', '-',
'0', '.', '=', '+',]
positions = [(i, j) for i in range(5) for j in range(4)]
for position, name in zip(positions, names):
if name == '':
continue
button = QPushButton(name)
grid.addWidget(button, *position)
self.setWindowTitle('PyQt window')
self.show()
def main():
app = QApplication(sys.argv)
ex = Example()
inferenceObj = InferenceWidget()
inferenceObj.runinference_thread.join()
print("Thread exit")
sys.exit(app.exec_())
if __name__ == '__main__':
main()

Related

DelphiVCL for Python threading

Using DelphiVCL for Python it seems to be blocking threads.
Testing the code (below) I would expect it to output / update timing from the two - 2 - threads. However the VCL app seems to be blocking the other threads.
How can this be fixed to allow running background threads with VCL?
from delphivcl import *
import threading
from time import sleep, strftime as now
from datetime import datetime
FORMAT = '%Y-%m-%d %H:%M:%S'
class Thread(threading.Thread):
def __init__(self, parent, threadname):
super(Thread, self).__init__()
self._stop = threading.Event()
self.parent = parent
self.name = threadname
def run(self):
while not self._stop.is_set():
text = "{0} {1} {2}".format(now(FORMAT), self.name, str(self._stop.is_set()))
if self.parent:
self.parent.lblHello.Caption = text
else:
print(text, flush=True)
sleep(1)
print(now(FORMAT), self.name, str(self._stop.is_set()))
def stop(self):
self._stop.set()
class GUIApp(Form):
def __init__(self, owner):
self.OnDestroy = self.__form_ondestroy
self.lblHello = Label(self)
self.lblHello.SetProps(Parent=self)
self.thread = Thread(self, 'inside app')
self.thread.start()
self.lblTimer = Label(self)
self.lblTimer.SetProps(Parent=self)
self.lblTimer.Top = 16
self.timer = Timer(self)
self.timer.Interval = 1
self.timer.OnTimer = self.__form_timer
self.timer.Enabled = True
def __form_timer(self, sender):
self.lblTimer.Caption = datetime.utcnow().strftime(FORMAT + '.%f')[:-3]
def __form_ondestroy(self, sender):
self.thread.stop()
if __name__ == '__main__':
Application.Initialize()
Application.Title = "Hello Delphi VCL"
app = GUIApp(Application)
app.Show()
t2 = Thread(None, 'outside app')
t2.start()
FreeConsole()
Application.Run()
app.Destroy()
t2.stop()
EDIT: Adding a timer (code updated) to the VCL app starts the background threads.

PyQt Progress Bar Update using Thread

I've been writing a program that used a MyWindow(QTableWidget) with a thread. A progress bar is displayed above the sub-window(self.win) displayed as a pop-up.
I want a green bar on the status bar to be displayed consecutively, however after resetting the Spyder-kernel, the green bar does not output continuously. And I want to run the 'stop'/'continue' alternately every time I click the push button. This hasn't been resolved for almost three days.
import sys, time
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtCore import QThread, pyqtSignal, pyqtSlot, QRect
from PyQt5.QtWidgets import *
progVal = 0
class thread(QThread):
signalTh = pyqtSignal(int)
def __init__(self, *args):
super().__init__()
self.flag = True
def run(self):
global progVal
if self.flag:
self.signalTh.emit(progVal)
time.sleep(0.1)
def stop(self):
self.flag = False
self.quit()
self.wait(2)
class MyWindow(QTableWidget):
def __init__(self):
global progVal
super().__init__()
self.setupUi()
self.show()
self.test = thread(None)
self.test.signalTh.connect(self.signal_function)
self.test.run()
self.saveData()
def saveData(self):
global progVal
counts = range(1, 51)
for row in counts:
progVal = int(row/len(counts)*100)
self.test.signalTh.emit(progVal)
time.sleep(0.1)
def click1_function(self):
if self.test.flag:
self.test.stop()
self.pb_start.setText('Start!')
else:
self.test.flag = True
self.test.run()
self.pb_start.setText('Stop!')
#pyqtSlot(int)
def signal_function(self, val):
self.progress.setValue(val)
self.progress.update()
self.win.update()
self.update()
def setupUi(self):
self.resize(500, 400)
self.pb_start = QPushButton(self)
self.pb_start.setGeometry(QRect(80, 20, 100, 50))
self.pb_start.setText("Start")
self.pb_start.clicked.connect(self.click1_function)
self.win = QDialog(self)
self.win.resize(330, 100)
self.progress = QProgressBar(self.win)
self.progress.setGeometry(10, 10, 300, 30)
self.progress.setMaximum(100)
self.win.show()
def closeEvent(self, event):
quit_msg = "Are you sure you want to exit the program?"
reply = QMessageBox.question(self, 'Message', quit_msg, QMessageBox.Yes, QMessageBox.No)
if reply == QMessageBox.Yes:
self.test.stop()
event.accept()
else:
event.ignore()
if __name__ == "__main__":
app = QApplication(sys.argv)
myApp = MyWindow()
myApp.show()
app.exec_()

PySide2 works not efficient

from PySide2.QtWidgets import QApplication, QMainWindow,QDialog,QLineEdit,QPushButton
from PySide2.QtCore import Qt
import sys
from ui618 import Ui_MainWindow
from numpad import Ui_Dialog
class MyWindow:
def __init__(self) -> None:
self.lastSelectedEditLine = None
# main ui
self.MainWindow = QMainWindow()
self.ui = Ui_MainWindow()
self.ui.setupUi(self.MainWindow)
# numpad
self.QDialog = QDialog(self.MainWindow)
self.numpad = Ui_Dialog()
self.numpad.setupUi(self.QDialog)
self.QDialog.setWindowFlags(Qt.Popup)
# bind editline with numpad
self.lineEdits = self.MainWindow.findChildren(QLineEdit)
for item in self.lineEdits:
item.focusInEvent = lambda e,item=item:self.test(e,item)
def save_quit(self):
sys.exit()
def bindbtn(self):
self.ui.quit.clicked.connect(self.save_quit)
def numpad_btn(self,a,item):
if item.text() != '←':
self.lastSelectedEditLine.setText(self.lastSelectedEditLine.text()+item.text())
else:
self.lastSelectedEditLine.setText(self.lastSelectedEditLine.text()[:-1])
def bindNumpad(self):
numpad_btns = self.QDialog.findChildren(QPushButton)
for item in numpad_btns:
item.clicked.connect(lambda ignore='ignore',item=item : self.numpad_btn(ignore,item))
def test(self,e,item):
self.lastSelectedEditLine = item
this = item
x = self.MainWindow.x()
y = self.MainWindow.y() + self.ui.selectX.rect().bottom()
while this.parentWidget().objectName() != 'MainWindow':
x += this.x()
y += this.y()
this = this.parentWidget()
self.QDialog.move(x, y)
self.QDialog.show()
item.clearFocus()
def show(self):
self.MainWindow.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
myWindow = MyWindow()
myWindow.show()
myWindow.bindbtn()
myWindow.bindNumpad()
sys.exit(app.exec_())
The code works as expected, the numpad shows while focusing in a qlineedit. and can write and delete to target input line.
I am new to pyside2. Is there a better way to implement the numpad? I this way, the cursor is disable, I have to edit at the end of each editline.
It take several seconds while starting, Some one know how to improve it?

Showing a QSplashScreen with QMovie and a QProgressBar crashed. PyQt5

I try to display a SplashScreeen with a gif and a progressbar in it, while a method calculates.
Therefore I have one main.py with a PyQt5 MainWindow Application. In this application method starts, see my calc.py:
from time import sleep, time
import pandas as pd
import concurrent.futures, requests, queue, sys
from threading import Thread
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QIcon, QFont, QKeySequence, QPalette, QBrush, QColor, QPixmap, QMovie, QPainter
from PyQt5.QtCore import Qt, QSize, QRect, QThread, pyqtSignal, QTimer
class MovieSplashScreen(QSplashScreen):
def __init__(self, movie, parent = None):
movie.jumpToFrame(0)
pixmap = QPixmap(movie.frameRect().size())
QSplashScreen.__init__(self, pixmap)
self.movie = movie
self.movie.frameChanged.connect(self.repaint)
def showEvent(self, event):
self.movie.start()
def hideEvent(self, event):
self.movie.stop()
def paintEvent(self, event):
painter = QPainter(self)
pixmap = self.movie.currentPixmap()
self.setMask(pixmap.mask())
painter.drawPixmap(0, 0, pixmap)
def sizeHint(self):
return self.movie.scaledSize()
def splashScreen(zeit = 0):
print('===splashScreen(self)====')
dapp = QApplication(['a', 's'])
# Create and display the splash screen
movie = QMovie("img\\fuchs.gif")
if zeit <= 2:
gerundet = 50
elif zeit > 2:
gerundet = zeit * 60
print("gerundet = ", gerundet)
splash = MovieSplashScreen(movie)
width = splash.frameGeometry().width()
height = splash.frameGeometry().height()
x = splash.pos().x()
y = splash.pos().y()
print('splash x,y: ',width, height, x, y)
splash.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint)
splash.setEnabled(False)
# adding progress bar
palette = QPalette()
palette.setColor(QPalette.Highlight, Qt.green)
progressBar = QProgressBar()
progressBar.setMaximum(gerundet)
progressBar.setGeometry(x, y-30, width, 20)
progressBar.setPalette(palette)
progressBar.setWindowFlags(Qt.SplashScreen | Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
gerundet = gerundet + 1
#splash.setMask(splash_pix.mask())
progressBar.show()
splash.show()
splash.showMessage("<h1><font color='red'></font></h1>", Qt.AlignTop | Qt.AlignCenter, Qt.black)
for i in range(1, gerundet):
progressBar.setValue(i)
t = time()
while time() < t + 0.1:
dapp.processEvents()
progressBar.hide()
window = QWidget()
splash.finish(window)
dapp.deleteLater() # here are troubles maybe in cause of main.py with the GUI has a app = QAplllication(sys.argv) too?
def getSignals(selectedCoins, selectedCoinsText):
print("=====getFilteredSignals====")
dfFilter = []
noResults = []
print("selectedCoins: ", selectedCoins)
zeit = len(selectedCoins)
# Problems here?
t = Thread(target=splashScreen, args=(zeit,))
t.start()
for i in range(len(selectedCoins)):
print("i: "+str(i)+" ", selectedCoins[i])
if i >= 1:
sleep(6)
result = makeSignals(selectedCoins[i])
print("results.empty: ", result.empty)
if result.empty == False:
result = result.set_index('Pair', inplace=False)
dfFilter.append(result)
else:
print("selectedCoinsText"+str(i)+": ", selectedCoinsText[i])
noResults.append(selectedCoinsText[i])
print("\nlen(dfFilter): ", len(dfFilter))
if len(dfFilter) == 0:
print("\n\n====in if len(dfFilter) == 0: \n dfFilter: ", dfFilter)
# Creating an empty Dataframe with column names only
dfempty = pd.DataFrame(columns=['User_ID', 'UserName', 'Action'])
print("Empty Dataframe ", dfempty,'\n dfempty.empty: ', dfempty.empty)
return dfempty
elif len(dfFilter) > 0:
for i in range(len(dfFilter)):
print("\n\n====in for loop=== \n dfFilter ["+str(i)+"]: \n", dfFilter[i])
filteredResults = pd.concat(dfFilter, axis=0, sort=False)
#filteredResults['Gain (%)'] = pd.to_numeric(filteredResults['Gain (%)'], errors='coerce')
filteredResults = filteredResults.sort_values(by='Gain (%)', ascending=False, inplace=False)
filteredResults = filteredResults.reset_index(inplace=False)
print('\nfilteredResults: \n', filteredResults, "\n", filteredResults.dtypes)
return filteredResults
self.results = calc.getSignals( a, aText)
Splashscreen and progressebar are displayed, but then the gui freezes and crashed.
So from main.py calc.py is started.
main.py is a gui with app = Qapplication() and a MainWindow().
Looks like:
import calc
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.font = QFont("Helvetica", 9)
self.setFont(self.font)
...
self.getSignals(a, aText)
...
def getSignals(self, a, aText):
zeit = len(a)
self.results = calc.getSignals(a, aText)
if __name__ == '__main__':
app = QApplication(sys.argv)
app.setStyle('Fusion')
mw = MainWindow()
mw.show()
sys.exit(app.exec_())
I try to use dapp.exit(exec_()) instead of dapp.deleteLater() in calc.py , but it still crashed too.
You are confusing concepts:
The time consuming task must be executed in another thread, in your case that task is processing.
If you want to control the GUI with the information obtained in the other thread then you must use signals, in this case I have created 2 signals that send the value of the QProgressBar showing the windows, and the other one sends the result.
If you want to do periodic tasks then use a QTimer.
With the above the solution is:
import os
import threading
import time
from PyQt5 import QtCore, QtGui, QtWidgets
import pandas as pd
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
class MovieSplashScreen(QtWidgets.QSplashScreen):
def __init__(self, movie, parent=None):
self._movie = movie
self.movie.jumpToFrame(0)
pixmap = QtGui.QPixmap(movie.frameRect().size())
super(MovieSplashScreen, self).__init__(pixmap)
self.setParent(parent)
self.movie.frameChanged.connect(self.repaint)
#property
def movie(self):
return self._movie
def showEvent(self, event):
self.movie.start()
super(MovieSplashScreen, self).showEvent(event)
def hideEvent(self, event):
self.movie.stop()
super(MovieSplashScreen, self).hideEvent(event)
def paintEvent(self, event):
painter = QtGui.QPainter(self)
pixmap = self.movie.currentPixmap()
self.setMask(pixmap.mask())
painter.drawPixmap(0, 0, pixmap)
def sizeHint(self):
return self.movie.scaledSize()
class Processor(QtCore.QObject):
started = QtCore.pyqtSignal(int)
filteredResultsSignal = QtCore.pyqtSignal(pd.DataFrame)
def execute(self, selectedCoins, selectedCoinsText):
threading.Thread(
target=self._execute, args=(selectedCoins, selectedCoinsText)
).start()
def _execute(self, selectedCoins, selectedCoinsText):
print("=====getFilteredSignals====")
dfFilter = []
noResults = []
print("selectedCoins: ", selectedCoins)
zeit = len(selectedCoins)
self.started.emit(zeit)
for i, (coin, text) in enumerate(zip(selectedCoins, selectedCoinsText)):
print("i: {} {}".format(i, coin))
if i >= 6:
time.sleep(6)
result = makeSignals(selectedCoins[i])
print("results.empty: ", result.empty)
if not result.empty:
result = result.set_index("Pair", inplace=False)
dfFilter.append(result)
else:
print("selectedCoinsText{}: {}".format(i, text))
noResults.append(text)
print("\nlen(dfFilter): ", len(dfFilter))
if len(dfFilter) == 0:
print("\n\n====in if len(dfFilter) == 0: \n dfFilter: ", dfFilter)
# Creating an empty Dataframe with column names only
filteredResults = pd.DataFrame(columns=["User_ID", "UserName", "Action"])
print(
"Empty Dataframe ",
filteredResults,
"\n dfempty.empty: ",
filteredResults.empty,
)
elif len(dfFilter) > 0:
for i, df_filter in enumerate(dfFilter):
print(
"\n\n====in for loop=== \n dfFilter [{}]: \n{}".format(i, df_filter)
)
filteredResults = pd.concat(dfFilter, axis=0, sort=False)
# filteredResults['Gain (%)'] = pd.to_numeric(filteredResults['Gain (%)'], errors='coerce')
filteredResults = filteredResults.sort_values(
by="Gain (%)", ascending=False, inplace=False
)
filteredResults = filteredResults.reset_index(inplace=False)
print(
"\nfilteredResults: \n", filteredResults, "\n", filteredResults.dtypes
)
self.filteredResultsSignal.emit(filteredResults)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
font = QtGui.QFont("Helvetica", 9)
self.setFont(font)
self.processor = Processor(self)
self.processor.started.connect(self.on_started)
self.processor.filteredResultsSignal.connect(self.on_filteredResultsSignal)
self.processor.execute("a", "aText")
movie_path = os.path.join(CURRENT_DIR, "img", "fuchs.gif")
movie = QtGui.QMovie(movie_path)
self.splash = MovieSplashScreen(movie)
self.splash.setWindowFlags(
QtCore.Qt.WindowStaysOnTopHint | QtCore.Qt.FramelessWindowHint
)
self.splash.setEnabled(False)
# adding progress bar
palette = QtGui.QPalette()
palette.setColor(QtGui.QPalette.Highlight, QtCore.Qt.green)
self.progressBar = QtWidgets.QProgressBar()
self.progressBar.setPalette(palette)
self.progressBar.setWindowFlags(
QtCore.Qt.SplashScreen
| QtCore.Qt.FramelessWindowHint
| QtCore.Qt.WindowStaysOnTopHint
)
self.progressBar.move(self.splash.pos() + QtCore.QPoint(0, -30))
self.progressBar.resize(self.splash.width(), 30)
self.counter = 0
self.gerundet = 0
self.timer = QtCore.QTimer(interval=100, timeout=self.on_timeout)
#QtCore.pyqtSlot(pd.DataFrame)
def on_filteredResultsSignal(self, df):
print(df)
#QtCore.pyqtSlot()
#QtCore.pyqtSlot(int)
def on_started(self, zeit=0):
gerundet = 50 if zeit <= 2 else zeit + 60
print("gerundet = ", gerundet)
gerundet = gerundet + 1
self.progressBar.setMaximum(gerundet)
# splash.setMask(splash_pix.mask())
self.progressBar.show()
self.splash.show()
self.splash.showMessage(
"<h1><font color='red'></font></h1>",
QtCore.Qt.AlignTop | QtCore.Qt.AlignCenter,
QtCore.Qt.black,
)
self.counter = 1
self.gerundet = gerundet
self.timer.start()
#QtCore.pyqtSlot()
def on_timeout(self):
self.progressBar.setValue(self.counter)
self.counter += 1
if self.counter > self.gerundet:
self.timer.stop()
self.progressBar.hide()
self.splash.close()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
app.setStyle("Fusion")
mw = MainWindow()
mw.show()
sys.exit(app.exec_())

a serial port thread in pyQT5

The following is my code. I am trying to create a serial port thread in my pyQt5 GUI. I checked many examples. This is very helpful one Background thread with QThread in PyQt
I think I made a successful connection but I am confused about the signature.
SelectedItem is the selected port. The GUI is still freezing because of while loop.
I need some help. Thanks!
#!/usr/bin/env python3
#-*- coding:utf-8 -*-
# vim:fileencoding=utf-8
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from TTP_Monitor_GUI import Ui_MainWindow
import serial
import serial.tools.list_ports
import binascii
import glob
class SerialPort(QObject):
def __init__(self, parent = None):
super(SerialPort, self).__init__(parent)
# Explicit signal
newParams = pyqtSignal(str)
#pyqtSlot(str)
def ReadSerialPort(self, port):
#initialization and open the port
with serial.Serial(port, 115200, timeout=1) as ser:
print ("Starting up")
while True:
readOut = 0 #chars waiting from laser range finder
#readOut = ser.readline().decode('ascii')
readOut = ser.read(268) # Reads # Bytes
r = binascii.hexlify(readOut).decode('ascii')
print(r)
self.newParams.emit(r)
#ser.flush() #flush the buffer
if ser.isOpen() == False:
print("Serial Port is Close")
class Main(QMainWindow):
# Explicit Signal
#ser = pyqtSignal(str)
def __init__(self, parent=None):
super(QMainWindow, self).__init__(parent)
#QMainWindow.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.btnRefresh.clicked.connect(self.Refresh)
self.ui.btnConnect.clicked.connect(self.Connect)
self.ListFunction(self.SerialPorts())
# Implicit Slot
def Connect(self):
Items = self.ui.listMain.selectedItems()
if len(Items) != 1:
msg = QMessageBox()
msg.setIcon(QMessageBox.Critical)
msg.setWindowTitle("BE CAREFULL!")
msg.setText("SELECT ONLY 1 ITEM!...")
msg.exec_()
else:
SelectedItem = Items[0].text()
SelectedItem = SelectedItem.split(" ")[0]
if sys.platform.startswith('win') and SelectedItem[:3] != 'COM':
msg = QMessageBox()
msg.setIcon(QMessageBox.Critical)
msg.setWindowTitle("BE CAREFULL!")
msg.setText("THERE IS A MISTAKE!...")
msg.exec_()
return
# Read Selected Serial Port
self.serialThread = QThread()
self.ser = SerialPort()
self.ser.moveToThread(self.serialThread)
self.ser.newParams.connect(self.serialThread.quit)
#self.serialThread.started.connect(self.ser.ReadSerialPort(SelectedItem))
self.serialThread.started.connect(lambda port=SelectedItem: self.ser.ReadSerialPort(port))
self.serialThread.start()
def Refresh(self):
""" Refresh List Widget """
self.ui.listMain.clear()
if self.ui.radioSerialPorts.isChecked() == True:
self.ListFunction(self.SerialPorts())
elif self.ui.radioTCP.isChecked() == True:
pass
def ListFunction(self, items):
""" Lists items into List Widget """
if type(items) == list and type(items[0]) == str:
#qApp.processEvents() # See Changes on GUI
self.ui.listMain.addItems(items)
else:
msg = QMessageBox()
msg.setIcon(QMessageBox.Critical)
msg.setWindowTitle("BE CAREFULL!")
msg.setText("ITEMS ARE WRONG!...")
msg.exec_()
def SerialPorts(self):
""" Lists serial port names """
device = []
description = []
result = []
for port in serial.tools.list_ports.comports():
device.append(port.device)
description.append(port.description)
result.append(port.device + ' - ' + port.description)
return result
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
myapp = Main()
myapp.show()
sys.exit(app.exec_())
provide delay function time.sleep(1) at thread function ReadSerialPort(self, port) inside the while loop äfter the function self.newParams.emit(r).
pyqt UI does not gets sufficient time to execute. so provide delay. it will work.

Resources