PyQt QTreeWidget.clear () crashes

I have python 2.5 and PyQt 4.8.6 installed. Os - Windows Xp Sp2. I use the following code to populate a TreeWidget:

def updateTreeWidget(self, widget, results): """ Updates the widget with given results """ widget.clear() for item in results: temp = QtGui.QTreeWidgetItem() j = 0 for elem in item: temp.setText(j , str(elem)) j += 1 widget.addTopLevelItem(temp) for column in range(widget.columnCount()): widget.resizeColumnToContents(column) 

It causes failures during the second use. If I comment on one of the following lines:

 widget.addTopLevelItem(temp) 

or

 widget.clear() 

It works without problems.

I call a function in a thread every 60 seconds. Here is the definition of the MyThread class.

 class MyThread(threading.Thread): def __init__(self, db, widget, function, script, parameter): threading.Thread.__init__(self) self.db = db self.function = function self.script = script self.parameter = parameter self.widget = widget self.event = threading.Event() def run(self): while 1: self.event.wait(60) parameter = [getCurrentTimeStr()] + self.parameter res = self.db.getQuery(self.script % tuple(parameter)) self.function(self.widget, res) 

This thread starts when in the main window init ():

 class MainWnd(QtGui.QMainWindow): def __init__(self, parent = None): # some code self.db = DbAccess() QtGui.QWidget.__init__(self, parent) self.ui = Ui_mainWnd() self.ui.setupUi(self) self.thread = MyThread(self.db, self.ui.treeWidget, self.updateTreeWidget, self.script, self.param) self.thread.start() 

The widget was created using Qt Designer.

+4
source share
1 answer

Updating GUI elements from a thread that does not match the Qt event loop is a big, no-no.

The usual way to solve this problem is to use a signal / slot queue or a single QTimer to transfer the boundaries of the threads and execute your function in the main thread.

+2
source

Source: https://habr.com/ru/post/1387383/


All Articles