Search code examples
pythonqtpyqtqtablewidgetpyqt6

How to get the number of the highlighted row in QTableWidget?


In pyqt6 how do I get the row that is highlighted in the QTableWidget when I move the arrow keys?

enter image description here

The tableWidget.currentRow() command only returns the row when I click on it.


Solution

  • You should use QTableWidget().itemSelectionChanged.connect() to easily retrieve the selection with arrow keys. https://doc.qt.io/qt-6/qtablewidget.html I use PySide2, but I think it should be the same with pyqt6. My example :

    import sys
    from functools import partial
    from PySide2.QtCore import *
    from PySide2.QtGui import *
    from PySide2.QtWidgets import *
    import random 
    import string
    
    _datas = []
    for i in range(10): 
        nmb = f"{random.randrange(123, 9999)}".zfill(6)
        text = ''.join(random.choice(string.ascii_lowercase) for j in range(5))
        _datas.append((nmb, text))
    
    class MY_APP(QMainWindow) :
        def __init__(self, ):
            super().__init__()
            self.create_ui()
            self.setup_connection()
    
        def create_ui(self):
            self.resize(QSize(500, 600))
            central_wid = QWidget()
            
            self.setCentralWidget(central_wid)
    
            central_wid.setLayout(QHBoxLayout())
            self.my_table = QTableWidget()
            self.my_table.setAlternatingRowColors(True)
            self.my_table.setSelectionMode(QTableWidget.ExtendedSelection)
            self.my_table.setSelectionBehavior(QAbstractItemView.SelectRows)
            self.my_table.horizontalHeader().setStretchLastSection(True)
            self.my_table.setColumnCount(2)
            for row, _d in enumerate(_datas) : 
                self.my_table.insertRow(row)
                for col, col_value in enumerate(_d) : 
                    item = QTableWidgetItem()
                    item.setText(col_value)
                    self.my_table.setItem(row, col, item)
    
            central_wid.layout().addWidget(self.my_table)
    
            self.reportView = QPlainTextEdit()
            central_wid.layout().addWidget(self.reportView)
    
    
        def setup_connection(self): 
            # connected function to item selection changed trigger of my_table
            self.my_table.itemSelectionChanged.connect(self.action_report_in_view)
    
        def action_report_in_view(self, *arg):
            values = []
            for selected_item in self.my_table.selectedItems():
                # create [item from col 0, item from col 1]
                values.insert(selected_item.column(), selected_item.text())
            self.add_to_log(values)
    
        def add_to_log(self, value):
            self.reportView.appendPlainText(str(value))
            
    app = QApplication(sys.argv)
    window = MY_APP()
    window.show()
    
    sys.exit(app.exec_())
    

    enter image description here