2015-04-22 29 views
0

我現在正在試圖使我的PC上的GUI與每個套接字的服務器進行通信。PySide QTextEdit或QPlainTextEdit更新更快?

這裏是GUI的部分代碼:

def listenToServer(self): 
    """ keep listening to the server until receiving 'All Contracts Finished' """ 
    self.feedbackWindow.appendPlainText('--Executing the Contracts, Listening to Server--') 
    contentsListend = '' 
    while contentsListend != 'All Contracts Finished': 
     #keep listen from the socket 
     contentsListend = self.skt.recv(1024) 
     #make the GUI show the text 
     self.feedbackWindow.appendPlainText(contentsListend) 

在另一邊,服務器將通過一個但也有一些時間間隔發送的數據之一。下面是測試代碼模擬服務器:

現在
for i in range(7): 
    print 'send back msg, round: ', i # this will be printed on the screen of the server, to let me know that the server works 
    time.sleep(1) # make some interval 
    # c is the connected socket, which can send messages 
    # just send the current loop number 
    c.send('send back msg' + str(i)) 
c.send('All Contracts Finished') 
c.close()# Close the connection 

,一切正常,只是,在GUI僅將全在服務器循環後顯示接收到的信息的問題。 一旦我運行服務器和GUI。服務器端以正確的速度逐個將消息打印到屏幕上,但GUI沒有響應,不更新。直到程序結束,所有7行全部在GUI一邊全部出現。我希望它們一個接一個地出現,這樣以後我可以在PC上用這個GUI檢查服務器的狀態。

任何人都可以幫忙,非常感謝!

回答

0

這與「快」或「慢」無關。

GUI運行在與您的listenToServer方法相同的線程上 - 只要運行在GUI線程上什麼都不會發生。您會注意到,在等待套接字輸入時,您無法移動,調整大小或單擊GUI中的任何內容。

您必須在獨立於GUI的線程上運行listenToServer方法。正確的做法是實現一個從套接字接收數據的Worker對象,並通過Signal-> Slot連接通知您textEdit數據已準備好接收。

我回答過類似的問題而回,這可能有助於 https://stackoverflow.com/a/24821300/2319400

一個真的快速和骯髒的替代辦法是處理所有排隊的事件,當你追加新的數據,通過:

QApplication.processEvents() 

這給Qt時間,例如用新的文本在屏幕上重新繪製GUI。 然而,當python等待數據來自套接字時,您的GUI將不會響應任何事件!

+0

很好的答案!真的很有幫助。所以我必須使用線程....非常感謝! – Richard