Skip to content Skip to sidebar Skip to footer

Introduce A Text In A Lineedit Of Pyqt From A Thread

How can I introduce a text in a lineEdit from a thread that are getting the data whithout colapse the program? The important line is in the class 'fil' where it shows Principal.sel

Solution 1:

You can use signals. You would add a signal to the fil class that emits the new text:

classfil(threading.Thread):
    update_line_edit = pyqtSignal(str)
    def__init__(self, temp, serie, line):
        ...

    defrun(self):
        try:
            whileTrue:
                self.temp = self.serie.readline()
                ifnot self.temp:
                    update_line_edit.emit(self.temp)
        ...

Then, simply connect that signal to a slot function in your Principal class:

classPrincipal(QtGui.QWidget):def__init__(self):
        ...

    defconnectar(self):
        try:
            arduino = serial.Serial('/dev/ttyACM0', 9600)
            print "Connectat amb èxit"
            temperatura = fil(0, arduino, self.aplicacio.actual_lineEdit)
            temperatura.change_line_edit.connect(self.update_line_edit)
        ...

    defupdate_line_edit(self, text):
        self.aplicacio.actual_lineEdit.setText(text)

Solution 2:

There are a few ways to do this correctly.

The first is to use a QThread instead of a python thread. You can then use Qt signals to pass a message back from the fil thread to the Qt MainThread and append the message to the QLineEdit there. Another similar approach is to continue using a Python thread, but place your message in a Python Queue.Queue() object. This Queue is then read by a secondary QThread, whose sole purpose is to read messages out of the Queue and emit a signal back to the MainThread.

The common feature of these two methods is that you only access Qt GUI objects from the MainThread and use signals/slots to communicate between threads. Here are some other questions where I've answered similar questions (you should be able to adapt them to your program):

However, since answering those questions, my colleagues and I have created a project that helps simplify writing multi-threaded Qt applications. The project is called qtutils and is on PyPi so it can be installed with pip or easy_install (just run pip install qtutils or easy_install qtutils from a commandline/terminal window).

This library has (among others) some functions inmain and inmain_later which will run a specified method in the Qt MainThread (regardless of the thread the call is made from) synchronously or asynchronously. Documentation on how to use these methods is here. I've modified your example code to use my inmain method and put the code here: http://pastebin.com/QM1Y6zBx -- obviously you need to install qtutils for it to work!

Post a Comment for "Introduce A Text In A Lineedit Of Pyqt From A Thread"