Get value from QTableWidget
-
Hello,
I am using PySide2 and have a QTableWidget that is connected to my database. I have implemented a search functionality. The selection method is that entire row is selected.
I want to implement functionality that whenever a row is selected and then the user presses a button, I should be able to get the first column of that selected row.
It's basically the primary key of the record in my database. Once I have the ID, I will be able to do anything I like with it.Is this possible to implement?
I tried using 'self.tableWidget.selectedItems()' but it just returns something like:
[<PySide2.QtWidgets.QTableWidgetItem object at 0x000002553F2B4140>, <PySide2.QtWidgets.QTableWidgetItem object at 0x000002553F2B4100>, <PySide2.QtWidgets.QTableWidgetItem object at 0x000002553F2B4180>, <PySide2.QtWidgets.QTableWidgetItem object at 0x000002553F2B41C0>, <PySide2.QtWidgets.QTableWidgetItem object at 0x000002553F2B4200>]
-
@lolcocks
The list ofQTableWidgetItem
you are getting back fromselectedItems()
represents one entry for each column in the expected order from the selected row. So, if you take the first list element and use eitherQTableWidgetItem.text()
orQTableWidgetItem.data(...)
you will get the value of the table cell. See the example below for a working example:from PySide2.QtCore import Slot from PySide2.QtWidgets import ( QWidget, QVBoxLayout, QTableWidget, QTableWidgetItem, QPushButton, QMessageBox, ) class Widget(QWidget): def __init__(self, parent=None, **kwargs): super().__init__(parent, **kwargs) l = QVBoxLayout(self) # Create a blank 10x5 table self._tableWidget = QTableWidget(10, 5, self) # Create some test data, simply the text '(row,col)' for each cell for row in range(10): for col in range(5): self._tableWidget.setItem( row, col, QTableWidgetItem(f"({row+1},{col+1})") ) self._tableWidget.setSelectionBehavior(QTableWidget.SelectRows) l.addWidget(self._tableWidget) l.addWidget(QPushButton("Selected", self, clicked=self.getSelectedItems)) @Slot() def getSelectedItems(self): try: # Get the first QTableWidgetItem from the selected row or catch the # exception if no row is selected. firstColValue: QTableWidgetItem = self._tableWidget.selectedItems()[0] except IndexError: return # Show a message box with the .text() value of the QTableWidgetItem QMessageBox.information( self, "Column Value", f"1st Column Value: {firstColValue.text()}" ) if __name__ == "__main__": from sys import argv, exit from PySide2.QtWidgets import QApplication a = QApplication(argv) m = Widget() m.show() exit(a.exec_())
Hope this helps ;o)