在页面加载中在 pyqt5 上设置表值会引发 AttributeError

问题描述

我正在尝试使用辅助类和方法页面加载上设置 pyqt5 Qtablewidget 项目。这是我的代码

#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

但是这会返回错误 AttributeError: 'nonetype' object has no attribute 'setText'

难道不能在这样的单独类中设置 ui 元素吗?迁移到单独的辅助类的原因主要是为了减少在主 ui 类中堵塞的代码

解决方法

空单元格的存在并不意味着它与 QTableWidgetItem 相关联,因此 item() 方法返回 None。一个可能的解决方案是检查它是否为 None,如果是,则创建 QTableWidgetItem 并使用 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

另一种可能的解决方案是使用模型,如果每个单元格都与一个 QModelIndex 相关联:

def setExamRecords(self,key in enumerate(exam):
            index = ui.tableWidget.model().index(rowIndex,colIndex)
            ui.tableWidget.model().setData(index,str(exam[key]))
    return True