so I have a QTextEdit within a Main Window in my GUI. I want to live update the text in this by pulling from a remotely updating list. I don't know how to infinitely check this list, without either a) doing an infinite loop or b) thread.
a) Crashes the GUI, as it is an infinite loop
b) produces an error saying:
QObject: Cannot create children for a parent that is in a different thread.
Which I understand.
What could I do to fix this?
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_()