首页 > 解决方案 > QTableWidget setText 返回属性错误

问题描述

我的问题类似于PyQt - QTableWidget 的 setText 方法获取 AttributeError。但是,在这种情况下,解决方案不起作用。

我正在尝试自动重写一些字段,其中要设置的值保存在数组中。因为我有一些空行,所以我遍历这些行以确保名称与将要设置的值相关。

    #statsPlayer is a class that holds the array through a getter method
    #modelTable is the QTableWidget
    #possibilities is the array that holds the names of the rows that are to be modified

    possiblities = ['Tackles', 'Blocks', 'Interceptions', 'Passes', 'Succesful Dribbles', 'Fouls Drawn', 'Goals', 'Assists', 'Penalties Scored']

    counterTracker = 0
    statsGroup = statsPlayer.statsGetter()[0]


    for row in range(modelTable.rowCount()):


        if modelTable.verticalHeaderItem(row).text() in possiblities:

            modelTable.item(row, 0).setText(str(statsGroup[counterTracker]))
            counterTracker += 1

我的问题是在前 3 行(铲球、拦网和拦截)之后,我收到一个属性错误:

AttributeError: 'NoneType' object has no attribute 'setText'

我试图修改的字段是空的,所以它们自然会是 None。但为什么我可以编辑前 3 个值而不能编辑其余的值?

标签: pythonpyside2qtablewidget

解决方案


QTableWidget 中的项目始终存在None,直到为它们设置了任何数据(或 QTableWidgetItem)。

只需添加一个检查以确保该项目存在,如果不存在,则创建它并为表设置它:

    item = modelTable.item(row, 0)
    if not item:
        item = QtWidgets.QTableWidgetItem()
        modelTable.setItem(row, 0, item)
    item.setText(str(statsGroup[counterTracker]))

推荐阅读