2016-12-30 31 views
0

我開發了一個多線程的gui,可以在單獨的線程中讀取串行數據。一般來說,我對線程,pyqt,python都很陌生。我用這個網站作爲參考,以獲得這個遠,它的工作正常,但研究如何添加第二個線程,我發現了一些文章和帖子,你不應該子類線程。我將如何將其轉換爲「正確」的方法?正確使用Qthread子類化工作,更好的方法?

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) 

回答

1

下面是從Qt文檔的文章,你會發現有用的 http://doc.qt.io/qt-4.8/thread-basics.html

有一個名爲款「哪個Qt中的線程技術要你何用?」 conataining一個表,建議使用什麼樣的方法取決於你想實現什麼

可能在你的情況下,你可能需要按照表中最後兩行描述的方法之一。

如果是這種情況,那麼你的代碼應該是這樣的

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() 
+0

此引用和代碼幫助了我極大。我現在更瞭解它。 – kaminsknator

相關問題