Reputation: 2862
I am trying to set pyqt5 Qtablewidget items on pageload using a helper class and method. This is my code.
#ui - > UI mainwindow class
#examdetails -> a list of dictionaries (table from database)
def setExamRecords(self,ui,examDetails):
for rowIndex,exam in enumerate(examDetails):
for colIndex,key in enumerate(exam):
print(exam[key])
item = ui.tableWidget.item(rowIndex, colIndex)
item.setText(str(exam[key]))
return True
However this returns error AttributeError: 'NoneType' object has no attribute 'setText'
is it not possible to set the ui elements in a separate class like this? The reason to moving to a separate helper class is mainly to reduce the codes clogging up in the main ui class.
Upvotes: 0
Views: 90
Reputation: 244162
The existence of an empty cell does not imply that it is associated with a QTableWidgetItem, therefore the item() method returns None. A possible solution is to check if it is None or not, if it is then create the QTableWidgetItem and set it with setItem():
def setExamRecords(self, ui, examDetails):
for rowIndex, exam in enumerate(examDetails):
for colIndex, key in enumerate(exam):
print(exam[key])
item = ui.tableWidget.item(rowIndex, colIndex)
if item is None:
item = QTableWidgetItem()
ui.tableWidget.setItem(rowIndex, colIndex, item)
item.setText(str(exam[key]))
return True
Another possible solution is to use the model where if each cell is associated with a QModelIndex:
def setExamRecords(self, ui, examDetails):
for rowIndex, exam in enumerate(examDetails):
for colIndex, key in enumerate(exam):
index = ui.tableWidget.model().index(rowIndex, colIndex)
ui.tableWidget.model().setData(index, str(exam[key]))
return True
Upvotes: 1