按 T​​ab 键或回车键时获取 QTableView 单元格值

Get QTableView cell value when pressing tab or enter key

我想在用户按下 Tab 或当用户将值放入单元格并按下 [= 时获取 QTableView 单元格的值19=]输入.

所以我写了下面的代码 - 但只有当我点击单元格时我才能得到值,而不是在按下 TabEnter[=23= 时].

    def table_config(self):
        setHeaders = ("CANTIDAD", "UNIDAD", "DESCRIPCION", "PRECIO UNITARIO", "PRECIO TOTAL")
        self.tableWidget.setHorizontalHeaderLabels(setHeaders)
        self.tableWidget.wordWrap()
        self.tableWidget.alternatingRowColors()
        self.tableWidget.clicked.connect(self.dataCell)

    def dataCell(self, item):
        data = item.data() # I got the value of the cell only when i clicked in it.
        print(data)

一种可能的解决方案是覆盖 keyPressEvent 方法并按按下的键进行过滤:

from PyQt5 import QtCore, QtGui, QtWidgets


class TableWidget(QtWidgets.QTableWidget):
    def keyPressEvent(self, event):
        super().keyPressEvent(event)
        if event.key() in (
            QtCore.Qt.Key_Tab,
            QtCore.Qt.Key_Return,
            QtCore.Qt.Key_Enter,
        ):
            it = self.currentItem()
            print(it)
            if it is not None:
                print(it.text())


class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.tableWidget = TableWidget(6, 6)

        for i in range(3):
            for j in range(2):
                it = QtWidgets.QTableWidgetItem("{}-{}".format(i, j))
                self.tableWidget.setItem(i, j, it)

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(self.tableWidget)
        lay.addWidget(QtWidgets.QLineEdit())
        lay.addWidget(QtWidgets.QSpinBox())


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)

    w = Widget()
    w.resize(640, 480)
    w.show()
    sys.exit(app.exec_())