Search code examples
pythonpyqt5qtablewidget

How to get the sum of items in selected index in PyQt5 QTableWidget


I would like to get the sum of selected items in the currentRow and show it on the same row of obviously a different column when the enter key is pressed

enter image description here

this is the code which get data from database

def pay1(self):
    con = mdb.connect(host='', user='',password='')
    cur = con.cursor()
    cur.execute("USE table_1")
    x = "SELECT player_name,total,time FROM paid"
    cur.execute(x)
    self.tableWidget.setRowCount(0)
    self.tableWidget.setColumnWidth(0, 100)
    self.tableWidget.setColumnWidth(1, 130)
    self.tableWidget.setColumnWidth(2, 130)
    self.tableWidget.setColumnWidth(3, 130)
    self.tableWidget.setHorizontalHeaderItem(0, 
    QtWidgets.QTableWidgetItem('Player Name'))
    self.tableWidget.setHorizontalHeaderItem(1, 
    QtWidgets.QTableWidgetItem('Total Amount'))
    self.tableWidget.setHorizontalHeaderItem(2, 
    QtWidgets.QTableWidgetItem('Time and Date'))

    for row_number, row_data in enumerate(cur):
        self.tableWidget.insertRow(row_number)
        for column_number, data in enumerate(row_data):
            self.tableWidget.setItem(row_number, column_number, 
            QtWidgets.QTableWidgetItem(str(data)))
    con.commit()

Solution

  • To capture the event of the pressed enter key you must use QShortCut, to obtain the selected items you must use the selectedIndexes() method of the QTableWidget as shown below:

    from PyQt5 import QtCore, QtGui, QtWidgets
    import random
    
    class Widget(QtWidgets.QWidget):
        def __init__(self, parent=None):
            super(Widget, self).__init__(parent)
            button = QtWidgets.QPushButton("Print me")
            self.tableWidget = QtWidgets.QTableWidget()
            lay = QtWidgets.QVBoxLayout(self)
            lay.addWidget(button)
            lay.addWidget(self.tableWidget)
            self.fill_table()
    
            QtWidgets.QShortcut(
                self.tableWidget,
                key=QtGui.QKeySequence(QtCore.Qt.Key_Return),
                context=QtCore.Qt.WidgetShortcut,
                activated=self.sum_selected
            )
    
        def fill_table(self):
            self.tableWidget.setColumnCount(4)
            self.tableWidget.setRowCount(0)
            for i, width in enumerate((100, 130, 130, 130)):
                self.tableWidget.setColumnWidth(i, width)
            self.tableWidget.setHorizontalHeaderLabels(['Player Name', 'Total Amount', 'Time and Date'])
    
            for i in range(40):
                self.tableWidget.insertRow(self.tableWidget.rowCount())
                it = QtWidgets.QTableWidgetItem(str(random.randint(100, 150)))
                self.tableWidget.setItem(i, 1, it)
    
        @QtCore.pyqtSlot()
        def sum_selected(self):
            result = sum([float(ix.data()) for ix in self.tableWidget.selectedIndexes() if ix.column() == 1])
            r, c = 0, 3
            it = self.tableWidget.item(r, c)
            if it is None:
                it = QtWidgets.QTableWidgetItem(str(result))
                self.tableWidget.setItem(r, c, it)
            else:
                it.setText(str(result))
    
    if __name__ == '__main__':
        import sys
        app = QtWidgets.QApplication(sys.argv)
        w = Widget()
        w.resize(640, 480)
        w.show()
        sys.exit(app.exec_())