[英]PYQT How get data from MainUiWindows to QThread?
我想知道如何從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()
但是有了這個,我只能在啟動該線程時獲得信息,正如我所說的,我想在她的迭代之間更改該變量。
感謝前進
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!”。 但是最后保存的值將是“再見!”,由線程完成。
希望對您有所幫助。 祝好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.