I am trying to build a PyQt5 application that would display a tree view and populate it dynamically on a button press. But it crashes (Process finished with exit code 134 (interrupted by signal 6: SIGABRT)) whenever I try to set or populate the model from within a function assigned to an action triggered signal (although it works just fine if I instantiate the model, load the data and assign the model to the TreeView in the window __init__
itself rather than in a function assigned to a signal). How do I achieve the desired behaviour? The whole model content (including the set of columns) is meant to completely change often during runtime. The UI is designed in Qt Designer and generated with pyuic5.
Here is my window code:
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
# model = MyModel() # UPDATE: useless, this wasn't here in the last pre-question version of the code actually
self.ui.actionLoad.triggered.connect(MainWindow.load) # UPDATE: Here is a mistake - should be self.load, not MainWindow.load
# @staticmethod # UPDATE: this wasn't here in the last pre-question version of the code actually
def load(self):
model = MyModel()
self.ui.treeViewLeft.setModel(model)
self.model.load() # UPDATE: Here is a mistake - should be model.load(), not self.model.load()
Here is my model code:
class MyModel(QStandardItemModel):
def __init__(self, *args, **kwargs):
super(MyModel, self).__init__(*args, **kwargs)
def load(self):
self.clear()
self.setHorizontalHeaderLabels(["Name", "Attr1", "Attr2"])
self.appendRow([QStandardItem('item1'), QStandardItem('attr11'), QStandardItem('attr21')])
self.appendRow([QStandardItem('item2'), QStandardItem('attr12'), QStandardItem('attr22')])
self.appendRow([QStandardItem('item3'), QStandardItem('attr13'), QStandardItem('attr23')])
I recommend you execute your code in the CMD or terminal in these cases since many IDEs have limitations in these cases. By running it you get this error message:
Traceback (most recent call last):
File "main.py", line 29, in load
self.ui.treeViewLeft.setModel(model)
AttributeError: 'bool' object has no attribute 'ui'
Aborted (core dumped)
A static method indicates that this method does not belong to an object of the class but to the class itself, and if you want to modify an object it should not be a static method so remove that decorator. On the other hand you must connect the signal to the slot by using self.
The solution is the next:
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
model = MyModel()
self.ui.actionLoad.triggered.connect(self.load)
def load(self):
model = MyModel(self)
self.ui.treeViewLeft.setModel(model)
model.load()