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

问题描述 投票:0回答:1

我想知道如何从MainUiWindows发送信息,比如从QlineEdit发送信息,并将其发送到QThread。我需要它在RealTime中,我希望每次我想要更改那些信息,并在QThread中更改变量。

我现在所拥有的是:

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

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

但是,当我启动此线程时,我只获取信息,正如我所说,我希望在她的迭代之间更改该变量。

谢谢你的进步

python pyqt qthread
1个回答
0
投票

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

要将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!”但最后保存的值将是“Good bye!”,由线程完成。

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

© www.soinside.com 2019 - 2024. All rights reserved.