如何在PyQt5 QTableWidget中获取选定索引中的项目总和

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

我想获取当前行中所选项目的总和,并在按下回车键时将其显示在明显不同列的同一行

这是从数据库中获取数据的代码

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()

要捕获按下回车键的事件,您必须使用 QShortCut,要获取所选项目,您必须使用 QTableWidgetselectedIndexes() 方法,如下所示:

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_())