Jorge Pereira
Jorge Pereira

Reputation: 11

PYQT How get data from MainUiWindows to QThread?

I want know how I can send information from the MainUiWindows, like from a QlineEdit, and send it to a QThread. I need it in RealTime, I want change that information everytime that I want and it change variable in that QThread.

What I have at moment is:

class ThreadClassControl(QtCore.QThread):
    def __init__(self):
        QThread.__init__(self)
        self.ui=MainUiClass()

    def run(self):
        print self.ui.QlineEdit.text()

But with that I only get the information when this Thread is started and as I said I want change that variable between her iterations.

Thanks for Advance

Upvotes: 0

Views: 1385

Answers (1)

edualvarado
edualvarado

Reputation: 353

Qt Widgets are not thread safe and you should not access them from any thread but the main thread (you can find more details in the Qt documentation). The correct way to use threads and Qt Widgets is via signals/slots.

To take values of the GUI to the second thread, you will need to assign them to this thread from the main thread (see in [1])

If case you want to modify such value in the thread, you need to use signals (see [2])

class MainThread(QtGui.QMainWindow, Ui_MainWindow):
    ...       
    def __init__(self, parent = None):
        ...
        # Create QLineEdit instance and assign string
        self.myLine = QLineEdit()
        self.myLine.setText("Hello World!")

        # Create thread instance and connect to signal to function
        self.myThread = ThreadClassControl()
        self.myThread.lineChanged.connect(self.myLine.setText) # <--- [2]
        ...

    def onStartThread(self):      
        # Before starting the thread, we assign the value of QLineEdit to the other thread
        self.myThread.line_thread = self.myLine.text() # <--- [1]

        print "Starting thread..."
        self.myThread.start()

    ... 

class ThreadClassControl(QtCore.QThread):
    # Declaration of the signals, with value type that will be used
    lineChanged = QtCore.pyqtSignal(str) # <--- [2]

    def __init__(self):
        QtCore.QThread.__init__(self)

    def __del__(self):
        self.wait()

    def run(self):
        print "---> Executing ThreadClassControl" 

        # Print the QLineEdit value assigned previously
        print "QLineEdit:", self.line_thread # <--- [1]

        # If you want to change the value of your QLineEdit, emit the Signal
        self.lineChanged.emit("Good bye!") # <--- [2]

As result, this program will print "Hello World!" but the last value saved will be "Good bye!", done by the thread.

I hope it helped. Good luck!

Upvotes: 1

Related Questions