如何动态更新QTextEdit

时间:2014-06-23 16:53:58

标签: python pyqt pyqt4 qtextedit

所以我在GUI的主窗口中有一个QTextEdit。我希望通过从远程更新列表中提取来更新此文本。我不知道如何无限地检查这个列表,没有a)做无限循环或b)线程。

a)崩溃GUI,因为它是一个无限循环 b)产生错误说:

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

我理解。

我该怎么做才能解决这个问题?

2 个答案:

答案 0 :(得分:8)

这是没有线程的方式:)

1)创建pyqt textEditor logView:

self.logView = QtGui.QTextEdit()

2)将pyqt texteditor添加到布局:

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_())

答案 1 :(得分:1)

转到QThread,毕竟将代码从python线程移动到QThread应该不难。 使用信号&插槽是imho唯一干净的解决方案。这就是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_()