[英]Proper use of Qthread subclassing works, better method?
我開發了一個多線程的gui,它可以在一個單獨的線程中讀取串行數據。 我對線程,pyqt和python非常陌生。 我使用此站點作為參考,以使它更深入地工作並能正常工作,但是研究如何添加第二個線程時,我發現了許多不應歸類於線程的文章和帖子。 我將如何將其轉換為“正確”方法?
class AThread(QtCore.QThread):
updated = QtCore.pyqtSignal(str)
query = QtCore.pyqtSignal(str)
def __init__(self):
QtCore.QThread.__init__(self)
def run(self):
try:
while True:
if ser.in_waiting:
line=ser.readline()[:-2]#remove end of line \r\n
self.updated.emit(line.decode('utf-8'))
if main_window.keywordCheckBox.isChecked():
if main_window.keywordInput.text() in line.decode('utf-8'):
self.query.emit("Match!")
self.query.emit(line.decode('utf-8'))
except serial.serialutil.SerialException:
pass
class MyMainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
self.thread= AThread()
self.thread.updated.connect(self.updateText)
self.thread.query.connect(self.matchFound)
這是Qt文檔中的文章,可能會對您有所幫助http://doc.qt.io/qt-4.8/thread-basics.html
有一個名為“您應該使用哪種Qt線程技術?”的段落。 包含一個表格,該表格根據您要實現的目標建議使用哪種方法
在您的情況下,可能需要遵循表最后兩行中描述的方法之一。
如果是這種情況,那么您的代碼應如下所示
class AWorker(QObject):
#define your signals here
def __init__(self):
super(AWorker, self).__init__()
def myfunction(self):
#Your code from run function goes here.
#Possibly instead of using True in your while loop you might
#better use a flag e.g while self.running:
#so that when you want to exit the application you can
#set the flag explicitly to false, and let the thread terminate
class MainWindow(...)
def __init__(...)
...
self.worker = AWorker()
self.thread = QThread()
self.worker.moveToThread(self.thread)
self.thread.started.connect(self.worker.myfunction)
#Now you can connect the signals of AWorker class to any slots here
#Also you might want to connect the finished signal of the thread
# to some slot in order to perform something when the thread
#finishes
#e.g,
self.thread.finished.connect(self.mythreadhasfinished)
#Finally you need to start the thread
self.thread.start()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.