You have two signals at your disposal in QtTableWidgets
to detect the change of content in a cell of the table:
-
QTableWidget.itemChanged
: Allows you to get the instance of QtTableWidget.Item
whose data were modified.
-
QTableWidget.cellChanged
: allows you to get the row and the column (indexes integers) of the cell in which is the item whose data were modified.
I leave an example of a table where the two signals are used, the slots only print the position of the cell, in them you can display the logic that allows you to do what you want to happen when you modify certain cells:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class Ejemplo(QtWidgets.QMainWindow):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.resize(690, 300)
self.centralwidget = QtWidgets.QWidget(self)
self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
self.tableWidget.setGeometry(QtCore.QRect(10, 10, 680, 290))
self.tableWidget.setColumnCount(5)
self.tableWidget.setRowCount(3)
self.tableWidget.setHorizontalHeaderLabels(['Col1', 'Col2', 'Col3', 'Col4', 'Col5'])
self.tableWidget.setVerticalHeaderLabels(["A", "B", "C"])
for i in range(3):
for j in range(5):
item = QtWidgets.QTableWidgetItem()
item.setText(str(i + j))
self.tableWidget.setItem(i, j, item)
self.setCentralWidget(self.centralwidget)
self.tableWidget.cellChanged.connect(self.on_cell_changed)
self.tableWidget.itemChanged.connect(self.on_item_changed)
@QtCore.pyqtSlot(int, int)
def on_cell_changed(self, row: int, col: int) -> None:
print(f"Se modificó la celda ({row}, {col})")
@QtCore.pyqtSlot(QtWidgets.QTableWidgetItem)
def on_item_changed(self, item: QtWidgets.QTableWidgetItem) -> None:
print(f"Se modificó el item en posición ({item.row()}, {item.column()})")
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
window = Ejemplo()
window.show()
sys.exit(app.exec_())