python - 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 个值而不能编辑其余的值?
解决方案
QTableWidget 中的项目始终存在None
,直到为它们设置了任何数据(或 QTableWidgetItem)。
只需添加一个检查以确保该项目存在,如果不存在,则创建它并为表设置它:
item = modelTable.item(row, 0)
if not item:
item = QtWidgets.QTableWidgetItem()
modelTable.setItem(row, 0, item)
item.setText(str(statsGroup[counterTracker]))
推荐阅读
- .net - 完整的 .NET Framework 上的 ASP.NET Core 2.1
- php - 根据组合框查询新数据,并在新文本框中显示
- ruby-on-rails - Rails form_with 错误(远程:真)
- reactjs - 将具有内部状态的对象作为 React 组件中的实例属性是一种不好的做法吗?
- node.js - 如何使用添加到数据库的新主题列表重新加载/重新初始化 Kafka Consumer
- javascript - 如何从未知列数的 ajax 渲染表
- python-2.7 - 索引超出范围,仅在函数 python 内
- javascript - 从标签中获取 href 属性
- asp.net - Elasticsearch 响应对机器人无效
- distance - 根据与 Netlogo 中具有特定值的补丁的距离设置变量值