PYQT如何将数据从MainUiWindows获取到QThread?

时间:2018-08-31 09:26:29

标签: python pyqt qthread

我想知道如何从MainUiWindows发送信息,例如从QlineEdit发送信息,并将其发送到QThread。我需要实时的信息,我想每次更改该信息,它就会更改该QThread中的变量。

我现在所拥有的是:

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

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

但是,只有在启动此线程时,我才获得信息,正如我所说的,我想在她的迭代之间更改该变量。

感谢进阶

1 个答案:

答案 0 :(得分:0)

Qt小部件不是线程安全的,您不应从任何线程(主线程)访问它们(您可以在Qt文档中找到更多详细信息)。使用线程和Qt小部件的正确方法是通过信号/插槽。

要将GUI的值带到第二个线程,您需要将它们从主线程分配给该线程(请参见[1])

如果要在线程中修改该值,则需要使用信号(请参见[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]

因此,此程序将打印“ Hello World!”。但最后保存的值将是该线程完成的“再见!”。

我希望能有所帮助。祝你好运!