Pollo Monroy
Pollo Monroy

Reputation: 13

Get QTableView cell value when pressing tab or enter key

I want to get the value of the cell of a QTableView when the user presses Tab or when the user puts a value into the cell and presses Enter.

view GUI image here

So I wrote the following code - but only I get the value when I click in the cell, not when pressing Tab or Enter.

    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)

Upvotes: 1

Views: 1154

Answers (1)

eyllanesc
eyllanesc

Reputation: 243897

One possible solution is to override the keyPressEvent method and filter by the key pressed:

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

Upvotes: 1

Related Questions