Getting a Value from a Model Using Row-Column Indices

How to retrieve data from a Qt model using row and column integers
Heads up! You've already completed this tutorial.

How do I retrieve a value from a QAbstractTableModel using a pair of integers (row and column), for example when clicking a button, rather than clicking on a cell in a QTableView?

When you're working with QTableView and a custom model, you'll often want to access data in the model programmatically — maybe in response to a button click, or as part of some background logic. You might think you can just pass the row and column numbers directly to the model's data() method, but that's not quite how Qt's model/view system works.

Understanding QModelIndex

Qt's model/view framework uses a special object called a QModelIndex to refer to a specific cell in a model. The data() method on a model doesn't accept raw row and column integers directly. Instead, it expects a QModelIndex as its first argument.

To get data from a model using row and column integers, you first create a QModelIndex from those integers using the model's .index() method. Then you pass that index to .data().

Here's the pattern:

python
index = self.model.index(0, 0)
value = self.model.data(index, Qt.ItemDataRole.DisplayRole)

That's it. The .index(row, column) method creates the QModelIndex for you, and then .data() uses that index to look up the value.

The second argument, Qt.ItemDataRole.DisplayRole, tells the model which role you want — in this case, the display text. If your model returns strings for DisplayRole, then value will be a string.

A complete working example

Let's put this together in a small application with a QTableView and a QPushButton. Clicking the button retrieves the value at row 0, column 0 from the model and prints it:

python
import sys

from PyQt6.QtCore import Qt, QAbstractTableModel
from PyQt6.QtWidgets import (
    QApplication,
    QMainWindow,
    QPushButton,
    QTableView,
    QVBoxLayout,
    QWidget,
)

class TableModel(QAbstractTableModel):
    def __init__(self, data):
        super().__init__()
        self._data = data

    def data(self, index, role):
        if role == Qt.ItemDataRole.DisplayRole:
            return self._data[index.row()][index.column()]

    def rowCount(self, index):
        return len(self._data)

    def columnCount(self, index):
        return len(self._data[0])

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Model Data Access Example")

        data = [
            ["Apple", "Red", "Sweet"],
            ["Banana", "Yellow", "Sweet"],
            ["Broccoli", "Green", "Bitter"],
        ]

        self.model = TableModel(data)

        self.table = QTableView()
        self.table.setModel(self.model)

        self.button = QPushButton("Get value at row 0, column 0")
        self.button.clicked.connect(self.get_value)

        layout = QVBoxLayout()
        layout.addWidget(self.table)
        layout.addWidget(self.button)

        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)

    def get_value(self):
        index = self.model.index(0, 0)
        value = self.model.data(index, Qt.ItemDataRole.DisplayRole)
        print(f"Value at row 0, column 0: {value}")

app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec())

When you run this and click the button, you'll see Value at row 0, column 0: Apple printed to the console.

PyQt/PySide Development Services — Stuck in development hell? I'll help you get your project focused, finished and released. Benefit from years of practical experience releasing software with Python.

Find out More

Accessing any cell

You can use any valid row and column values. For example, to get the value at row 2, column 1:

python
index = self.model.index(2, 1)
value = self.model.data(index, Qt.ItemDataRole.DisplayRole)
print(value)  # Output: Green

Just make sure the row and column are within the bounds of your data — otherwise the index won't be valid and you will get None back.

Summary

To retrieve data from a Qt table model using row and column integers:

  1. Create a QModelIndex using self.model.index(row, column).
  2. Pass that index to self.model.data(index, Qt.ItemDataRole.DisplayRole).

This two-step pattern — create the index, then query the data — is how Qt's model/view system is designed to work. Once you're comfortable with it, you can use the same approach to access data from any model, whether it's backed by a list, a NumPy array, or a Pandas DataFrame.

Packaging Python Applications with PyInstaller by Martin Fitzpatrick — This step-by-step guide walks you through packaging your own Python applications from simple examples to complete installers and signed executables.

More info Get the book

Well done, you've finished this tutorial! Mark As Complete
[[ user.completed.length ]] completed [[ user.streak+1 ]] day streak

PyQt/PySide Development Services

Stuck in development hell? I'll help you get your project focused, finished and released. Benefit from years of practical experience releasing software with Python.

Find out More

Martin Fitzpatrick

Getting a Value from a Model Using Row-Column Indices was written by Martin Fitzpatrick with contributions from Leo Well.

Martin Fitzpatrick has been developing Python/Qt apps for 8 years. Building desktop applications to make data-analysis tools more user-friendly, Python was the obvious choice. Starting with Tk, later moving to wxWidgets and finally adopting PyQt. Martin founded PythonGUIs to provide easy to follow GUI programming tutorials to the Python community. He has written a number of popular Python books on the subject.