2014-06-23 85 views
1

所以我在我的GUI中的主窗口中有一個QTextEdit。我想通過從遠程更新列表中拉取更新文本。我不知道如何無限檢查這個列表,沒有a)做無限循環或b)線程。QTextEdit:如何在沒有崩潰GUI的情況下在PyQt中動態更新

一個)崩潰的圖形用戶界面,因爲它是一個無限循環 b)中產生一個錯誤說:

QObject: Cannot create children for a parent that is in a different thread. 

其中我明白了。

我能做些什麼來解決這個問題?

+0

爲什麼不使用信號和插槽來動態更新GUI? – Trilarion

+1

[從線程引入PyQt的一行文本]中可能出現的重複(http://stackoverflow.com/questions/24266251/introduce-a-text-in-a-- lineedit-of-pyqt-from-a-線程) –

+0

另請參閱http://stackoverflow.com/questions/21071448/redirecting-stdout-and-stderr-to-a-pyqt4-qtextedit-from-a-secondary-thread(不是這個的重複,但是高度相關) –

回答

5

這是如何工作的無緒:)

1)創建PyQt的文本編輯日誌查看:

self.logView = QtGui.QTextEdit() 

2)PyQt的文本編輯添加到佈局:

layout = QtGui.QGridLayout() 
layout.addWidget(self.logView,-ROW NUMBER-,-COLUMN NUMBER-) 
self.setLayout(layout) 

3)魔術功能是:

def refresh_text_box(self,MYSTRING): 
    self.logView.append('started appending %s' % MYSTRING) #append string 
    QtGui.QApplication.processEvents() #update gui for pyqt 

調用上述功能在循環或直接傳遞級聯得到的線以上的功能是這樣的:

self.setLayout(layout) 
self.setGeometry(400, 100, 100, 400) 
QtGui.QApplication.processEvents()#update gui so that pyqt app loop completes and displays frame to user 
while(True): 
    refresh_text_box(MYSTRING)#MY_FUNCTION_CALL 
    MY_LOGIC 
#then your gui loop 
if __name__ == '__main__': 
app = QtGui.QApplication(sys.argv) 
dialog = MAIN_FUNCTION() 
sys.exit(dialog.exec_()) 
+0

這聽起來很有希望@hemraj。這也會刷新我在GUI中可能擁有的其他東西嗎?例如一個表格小部件。什麼循環,我會完全放在這? – sudobangbang

+0

感謝您的回答。 QtGui.QApplication.processEvents()解決了我的問題。 –

0

轉到了QThread,畢竟,從蟒蛇線程移動你的代碼QThread應該不難。 使用信號&插槽是唯一干淨的解決方案。這就是Qt的工作方式,如果你適應這種情況,事情會變得更加容易。 一個簡單的例子:

import sip 
sip.setapi('QString', 2) 

from PyQt4 import QtGui, QtCore 

class UpdateThread(QtCore.QThread): 

    received = QtCore.pyqtSignal([str], [unicode]) 

    def run(self): 
     while True: 
      self.sleep(1) # this would be replaced by real code, producing the new text... 
      self.received.emit('Hiho') 

if __name__ == '__main__': 

    app = QtGui.QApplication([]) 

    main = QtGui.QMainWindow() 
    text = QtGui.QTextEdit() 
    main.setCentralWidget(text) 

    # create the updating thread and connect 
    # it's received signal to append 
    # every received chunk of data/text will be appended to the text 
    t = UpdateThread() 
    t.received.connect(text.append) 
    t.start() 

    main.show() 
    app.exec_() 
相關問題