How to dynamically update QTextEdit

老子叫甜甜 提交于 2019-11-30 10:30:58

this is how it works without threads :)

1) Create pyqt textEditor logView:

self.logView = QtGui.QTextEdit()

2)add pyqt texteditor to layout:

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

3) the magic function is:

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

call above function in your loop or pass concatenated resultant string directly to above function like this:

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

Go for QThread, after all, moving your code from a python thread to QThread shouldn't be hard. Using signals & slots is imho the only clean solution for this. That's how Qt works and things are easier if you adapt to that. A simple example:

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_()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!