无法在 QTableWidget 中添加两列。错误 - DeprecationWarning:需要一个整数(得到类型 float)

Can't add two columns in QTableWidget. Error - DeprecationWarning: an integer is required (got type float)

我正在尝试使用 PyQt5 中的 QTableWidget 创建电子表格。我想将两列的值相加并在第三列中显示结果。但是我一直收到错误 DeprecationWarning: an integer is required (got type float). Implicit conversion to integers using __int__ is deprecated, and may be removed in a future version of Python.

这是我写的添加列的函数。

def add_columns(self):
        new_cols = self.tableWidget.columnCount()
        for self.row in range (self.tableWidget.rowCount()):
            add_2_cols = float((self.tableWidget.item(self.row, 0)).text()) + float((self.tableWidget.item(self.row, 1)).text())
            add_2_cols = QTableWidgetItem(add_2_cols)
            self.tableWidget.setItem(self.row, 3, add_2_cols)

或者,如果有预设功能可以做到这一点,但我找不到。

那是因为您正在尝试使用求和结果(浮点数)作为第一个参数来创建 QTableWidgetItem。

QTableWidgetItem 的

One of the constructors 接受一个 整数 .
来自文档的 "Subclassing" section

When subclassing QTableWidgetItem to provide custom items, it is possible to define new types for them so that they can be distinguished from standard items. The constructors for subclasses that require this feature need to call the base class constructor with a new type value equal to or greater than UserType

因此,不仅您提供了无效的类型(因为它应该是整数),而且您使用它的原因也有误。

如果要创建一个以结果作为文本的项,必须将其转换为字符串:

add_2_cols = QTableWidgetItem(str(add_2_cols))

或者,您可以创建一个“空”项并使用 setData() 设置其显示值,同时以数字形式存储它:

add_2_cols = QTableWidgetItem()
add_2_cols.setData(QtCore.Qt.DisplayRole, add_2_cols)

这仍然会让 text() 使用该项目,但好处是您可以使用 data() 获得正确的数值,而无需冒任何转换的风险:

item = self.tableWidget.item(row, column)
if item:
    value = item.data(QtCore.Qt.DisplayRole)

在不相关的说明中,通常不建议在 for 循环中设置实例属性(就像您对 self.row 所做的那样):首先,如果使用不当,它可能会导致意外行为、错误和崩溃;而且,由于每次迭代都会覆盖以前的引用,因此拥有“静态”引用完全没有意义。