0

I am trying to listen a serial port and write the listened things to QPlainTextEdit item in Qt, real-time. For that, I have created a thread that listens and writes what it listens to the QPlainTextEdit item using the method I created.

Thread:

def readPort_thread(self):
    while self.printerOnline == True:
        self.writeTerminal(str(self.ser.readline(),'utf-8'))

QPlainTextEdit writer method:

def writeTerminal(self,inputTxt):
    if not inputTxt.endswith('\n'):
        inputTxt = inputTxt + '\n'
    self.textG.setPlainText(self.textG.toPlainText() + inputTxt)
    self.textG.verticalScrollBar().setValue(self.textG.verticalScrollBar().maximum() - 1)

So, I have tried couple of different things and looked for web for it but couldn't find anything. As I understood, the problem is calling Qt element method from a thread. I am new to Qt. Thanks.

salimsah
  • 1
  • 2
  • 1
    UI elements (for any UI toolkit, not only Qt) are not thread safe. Trying to access them from external threads will usually result in unexpected behavior, drawing artifacts and crashes. The ***only*** safe way to access a widget is through proper usage of signals and slots (so, you probably need to use a QThread, as normal python threads are usually not enough): you create signal for the QThread subclass, and you emit that signal from the `run` implementation, then you connect that signal to the function that actually updates the widget. For more specific answers, you need to provide a [mre]. – musicamante Oct 19 '21 at 22:58
  • You cannot write directly from a thread. But this is a classical usecase for signals and slots. Just emit some signal from the thread and if it is connected to a method in the main thread, then this method in the main thread can write to QPlainTextEdit. – HiFile.app - best file manager Oct 21 '21 at 22:11

0 Answers0