2011-11-20 48 views
0

我有一個QMainWindow啓動QThread並等待來自網絡的數據。在接收任何數據時更新UI。pyqt主窗口從線程接收數據後不斷崩潰

問題是:它有時會崩潰。有時候不會,我只要開始它並等待數據。

這裏是線程類:

class ListenerThread(QtCore.QThread): 

     def __init__(self,host,port,window): 
      super(ListenerThread,self).__init__(window) 
      self.host = host 
      self.port = port 
      self.window = window 


     def run(self): 

      soc = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) 
      soc.bind((self.host, self.port)) 

      while True: 

      data, address = soc.recvfrom(9999) 
      print address 


      if data: 



       dataList = data.split("\\") 


       company = dataList[1] 
       projectName = dataList[2] 
       assets = dataList[3] 
       assetType = dataList[4] 
       assetName = dataList[5] 



      # parent here is the main window(the main thread) : updateCombo is a function that updates combo box inside the    main window 

       self.parent().updateCombo(self.window.comboBoxCompany,company) 
       self.parent().updateCombo(self.window.dropDownProjects,projectName) 

       self.parent().select(assets,assetName) 

爲什麼會這樣?請記住,主窗口本身工作正常。

函數(updateCombo)也正常工作(當你從它的類調用它)。

但我發送數據時主窗口不斷崩潰!任何想法爲什麼?

回答

3

GUI小部件只能從主線程訪問,這意味着調用QApplication.exec()的線程。從任何其他線程訪問GUI小部件 - 您對self.parent()的調用進行的操作 - 未定義行爲,在您的情況下,這意味着崩潰。

您用信號和插槽以安全的方式在後臺線程和GUI之間進行通信。

並請閱讀Qt的線程功能的文檔,因爲上面實際上是多線程的GUI應用程序,不僅在Qt的,但在任何其他GUI框架打交道時,也基本知識。

+0

現在工作正常。你是對的 。我不應該使用self.parent(),信號是關鍵,好工作! –