Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

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 of QTableWidgetItem you are getting back from selectedItems() represents one entry for each column in the expected order from the selected row. So, if you take the first list element and use either QTableWidgetItem.text() or QTableWidgetItem.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)


  • Banned

    Hey @lolcocks I will warn you that attaching your front-end (GUI or View) directly to your back-end (Database or Data Source or Model) is only going to cause issues later on and that using the MVC Methodology (which is googleable) is usually the best way to go for most (if not all) such implementations. I have examples that might help you as well as I can teach you the elements of solid programming that you might not be aware. I am currently running a free-online lab-classroom for Python-Qt if it would interest you, you could join. Just let me know. However if you could provide a MRE (Minimal Reproducible Example) of your specific situation I can show you how to implement it correctly.

    [Edit: removed text about super() which is off-topic and was unrequested - @AndyS]


Log in to reply