【问题标题】:How to get the sum of items in seletedIndexes in PyQt QTableWidget如何在 PyQt QTableWidget 中获取 seletedIndexes 中的项目总和
【发布时间】:2018-06-01 11:50:31
【问题描述】:

我正在尝试以类似于 ms excel 的方式使用 QTableWidget。我想获得 currentRow 中所有项目的总和,并将其显示在明显不同列的同一行上。 这是我的代码

item = self.tableWidget.selectedIndexes()
table = QtGui.QTableWidgetItem()
row = self.tableWidget.currentRow()
table.setText(sum(item))
self.tableWidget.setItem(row, 5, table)

我收到此错误:

    table.setText(sum(data))
TypeError: unsupported operand type(s) for +: 'int' and 'QModelIndex'

【问题讨论】:

  • 请输入适当的代码,以下代码缺少括号:table.setText(sum(item):P
  • 我添加了忘记的括号
  • 您希望何时计算总和,何时按下按钮或某个键?
  • 我正在使用带有项目变量的代码的第一行,即:item = self.tableWidget.selectedIndexes()。如果可以解决我的问题,我也可以使用按钮
  • 当项目被选中时,我有一个使用上面提供的代码的右键单击选项。求和工作的 righticlick 选项,但代码显示问题前面通知的错误

标签: python pyqt pyqt4 qtablewidget


【解决方案1】:

selectedIndexes 返回与项目选择关联的QModelIndex,这些元素不能添加,因为它们是指示项目位置的元素,适当的方法是使用返回选定项目的selectedItems(),但这些都不是必须添加项目,您应该做的是获取文本并将其转换为浮点数并添加这些值:

val = sum([float(item.text()) for item in self.tableWidget.selectedItems()])
table = QtGui.QTableWidgetItem()
table.setText(str(val))
row = self.tableWidget.currentRow()
self.tableWidget.setItem(row, 5, table)

注意:我假设单元格中包含的值代表数字。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 2012-08-07
    • 2016-03-19
    • 2016-03-26
    • 2017-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多