Search code examples
pythonpyqtpyqt4qtablewidget

How to get the sum of items in seletedIndexes in PyQt QTableWidget


Am trying to use QTableWidget in a kind of similar way to ms excel. I would like to get the sum of all items in the currentRow and show it on the same row of obviously a different column. Here is my code

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

I get this error:

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

Solution

  • selectedIndexes returns the QModelIndex associated with the items selections, and these elements can not be added since they are elements that indicate the position of the item, an appropriate method is to use selectedItems () that returns the selected items, but neither those items must be added, what you should do is get the text and convert it to float and just add those values:

    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)
    

    Note: I have assumed that the values contained in the cells represent numbers.