PyQt-QTableWidget的setText方法获取AttributeError [英] PyQt - setText method of QTableWidget gets AttributeError

查看:183
本文介绍了PyQt-QTableWidget的setText方法获取AttributeError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用pyuic从Qt Designer编译了一个GUI文件,然后试图弄清楚如何用相同的"n" 值设置第一列中的所有单元格.

I used pyuic to compile a GUI file from Qt Designer, and I tried to figure out how to set all the cells in the first column with the same value "n".

以下是我的代码:

class Ui_MainWindow(object):
    ...
    def accinit(self):
        for n in xrange(9):
            item = self.tableWidget.item(n, 0)
            item.setText(_translate("MainWindow", "n", None))

控制台输出:

AttributeError:"NoneType"对象没有属性"setText"

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

我仅更改了一个单元格(0,0)的代码,并且效果很好:

I changed the code for only one cell (0,0), and it works perfectly:

def accinit(self):
    item = self.tableWidget.item(0, 0)
    item.setText(_translate("MainWindow", "n", None))

(0,0)处的单元格具有内容"n" .

The cell at (0,0) has content "n".

我想也许在for循环中是不允许的,所以我将代码更改为:

I thought maybe that it's not allowed in a for loop, so I changed code to:

def accinit(self):
    for x in xrange(1):
        item = self.tableWidget.item(0, 0)
        item.setText(_translate("MainWindow", "n", None))

但是它仍然有效!为什么?

But it still works! Why?

我已经参考了以下文章(但仍然无法解决此错误):

I already referenced the following articles (but I still can't solve this error):

Python:属性错误-"NoneType"对象没有属性某物"

Python AttributeError:NoneType对象没有属性"close"

推荐答案

我不确定.但这可能会有所帮助.

I am not exactly sure. But this could help.

显示无类型对象错误

=>在执行tableWidget.item语句后,项目为None

=> item is None after the tableWidget.item statement is executed

=>对于某些n,在(n,0)处不存在任何项,因此该项不返回任何值

=> No item is present at (n, 0) for some n because of which it is returning none

但它适用于(0,0)

=>(0,0)已经存在一个项目

=> An item is already present at (0, 0)

=>检查您的tableWidget是否具有标题?如果它有标题,则有一个非无项目(0,0),因此您可以为其设置文本.因此,仅在(0,x)中有一个项目,并且它为(1,0)而不是(0,0)抛出NoneType错误.

=> Check if your tableWidget has headers? If it has headers there is a non-None item at (0, 0) and therefore you can set text for it. Therefore, there is an item only in (0, x), and it throws the NoneType error for (1, 0) and not for (0, 0).

可能的解决方案?或更正

创建一个新项目,然后使用tableWidget.setItem(...)进行必要的操作.像

Create a new item, and use tableWidget.setItem(...) to do the needful. Something like

for x in xrange(5):
    item = QTableWidgetItem()
    item.setText("blah blah")
    self.tableWidget.setItem(n, 0, item)

这篇关于PyQt-QTableWidget的setText方法获取AttributeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆