I am developing python GUI using pyqt5 table widget. How Can I obtain the rows and columns position of a selected region? Actually, In the default PyQt5 table widget, the selected region is highlighted with blue color. How can I get this blue rows and columns coordinate ? Thank you

1 Answers

eyllanesc On Best Solutions

There are several methods to obtain the rows and columns:

  • Use the selectedIndexes() method.
for ix in tablewidget.selectedIndexes():
    print(ix.row(), ix.column())
  • Use the selectedItems() method, unlike the previous method this does not return the empty items.
for it in tablewidget.selectedItems():
    print(it.row(), it.column())

If you want to obtain the rows and columns at the time of selection you must use the selectionChanged signal of the selectionModel associated with the QTableWidget. Unlike the previous methods, this also returns the deselected items.

from PyQt5 import QtCore, QtGui, QtWidgets

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.table = QtWidgets.QTableWidget(6, 6)

    @QtCore.pyqtSlot(QtCore.QItemSelection, QtCore.QItemSelection)
    def on_selectionChanged(self, selected, deselected):
        for ix in selected.indexes():
            print(ix.row(), ix.column())
        for ix in deselected.indexes():
            print(ix.row(), ix.column())

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()