PySide6.QtCore.QRangeModel

class QRangeModel

QRangeModel implements QAbstractItemModel for any C++ range. More

Inheritance diagram of PySide6.QtCore.QRangeModel

Added in version 6.10.

Synopsis

Properties

Methods

Signals

Note

This documentation may contain snippets that were automatically translated from C++ to Python. We always welcome contributions to the snippet translation. If you see an issue with the translation, you can also let us know by creating a ticket on https:/bugreports.qt.io/projects/PYSIDE

Detailed Description

Warning

This section contains snippets that were automatically translated from C++ to Python and may contain errors.

QRangeModel can make the data in any sequentially iterable C++ type available to the model/view framework of Qt. This makes it easy to display existing data structures in the Qt Widgets and Qt Quick item views, and to allow the user of the application to manipulate the data using a graphical user interface.

To use QRangeModel , instantiate it with a C++ range and set it as the model of one or more views:

std.array<int, 5> numbers = {1, 2, 3, 4, 5}
model = QRangeModel(numbers)
listView.setModel(model)

Constructing the model

The range can be any C++ type for which the standard methods std::begin and std::end are implemented, and for which the returned iterator type satisfies std::forward_iterator. Certain model operations will perform better if std::size is available, and if the iterator satisfies std::random_access_iterator.

The range must be provided when constructing the model; there is no API to set the range later, and there is no API to retrieve the range from the model. The range can be provided by value, reference wrapper, or pointer. How the model was constructed defines whether changes through the model API will modify the original data.

When constructed by value, the model makes a copy of the range, and QAbstractItemModel APIs that modify the model, such as setData() or insertRows() , have no impact on the original range.

model = QRangeModel(numbers)

As there is no API to retrieve the range again, constructing the model from a range by value is mostly only useful for displaying read-only data. Changes to the data can be monitored using the signals emitted by the model, such as dataChanged() .

To make modifications of the model affect the original range, provide the range either by pointer:

model = QRangeModel(numbers)

or through a reference wrapper:

model = QRangeModel(std::ref(numbers))

In this case, QAbstractItemModel APIs that modify the model also modify the range. Methods that modify the structure of the range, such as insertRows() or removeColumns() , use standard C++ container APIs resize(), insert(), erase(), in addition to dereferencing a mutating iterator to set or clear the data.

Note

Once the model has been constructed and passed on to a view, the range that the model operates on must no longer be modified directly. Views on the model wouldn’t be informed about the changes, and structural changes are likely to corrupt instances of QPersistentModelIndex that the model maintains.

The caller must make sure that the range’s lifetime exceeds the lifetime of the model.

Use smart pointers to make sure that the range is only deleted when all clients are done with it.

shared_numbers = std::make_shared<std::vector<int>>(numbers)
model = QRangeModel(shared_numbers)

QRangeModel supports both shared and unique pointers.

Read-only or mutable

For ranges that are const objects, for which access always yields constant values, or where the required container APIs are not available, QRangeModel implements write-access APIs to do nothing and return false. In the example using std::array, the model cannot add or remove rows, as the number of entries in a C++ array is fixed. But the values can be changed using setData() , and the user can trigger editing of the values in the list view. By making the array const, the values also become read-only.

std.array<int, 5> numbers = {1, 2, 3, 4, 5}

The values are also read-only if the element type is const, like in

std.array<int, 5> numbers = {1, 2, 3, 4, 5}

In the above examples using std::vector, the model can add or remove rows, and the data can be changed. Passing the range as a constant reference will make the model read-only.

model = QRangeModel(std::cref(numbers))

Note

If the values in the range are const, then it’s also not possible to remove or insert columns and rows through the QAbstractItemModel API. For more granular control, implement the C++ tuple protocol .

Rows and columns

The elements in the range are interpreted as rows of the model. Depending on the type of these row elements, QRangeModel exposes the range as a list, a table, or a tree.

If the row elements are simple values, then the range gets represented as a list.

numbers = {1, 2, 3, 4, 5}
QRangeModel model(numbers) # columnCount() == 1
listView = QListView()
listView.setModel(model)

If the type of the row elements is an iterable range, such as a vector, list, or array, then the range gets represented as a table.

std.vector<std.vector<int>> gridOfNumbers = {
    {1, 2, 3, 4, 5},
    {6, 7, 8, 9, 10},
    {11, 12, 13, 14, 15},

QRangeModel model(gridOfNumbers) # columnCount() == 5
tableView = QTableView()
tableView.setModel(model)

If the row type provides the standard C++ container APIs resize(), insert(), erase(), then columns can be added and removed via insertColumns() and removeColumns() . All rows are required to have the same number of columns.

Structs and gadgets as rows

If the row type implements the C++ tuple protocol , then the range gets represented as a table with a fixed number of columns.

TableRow = std::tuple<int, QString>
numberNames = {
    {1, "one"},
    {2, "two"},
    {3, "three"}

QRangeModel model(numberNames) # columnCount() == 2
tableView = QTableView()
tableView.setModel(model)

An easier and more flexible alternative to implementing the tuple protocol for a C++ type is to use Qt’s meta-object system to declare a type with properties . This can be a value type that is declared as a gadget , or a QObject subclass.

class Book():

    Q_GADGET
    Q_PROPERTY(QString title READ title)
    Q_PROPERTY(QString author READ author)
    Q_PROPERTY(QString summary MEMBER m_summary)
    Q_PROPERTY(int rating READ rating WRITE setRating)
# public
    Book(QString title, QString author)
    # C++ rule of 0: destructor, as well as copy/move operations
    # provided by the compiler.
    # read-only properties
    QString title() { return m_title; }
    QString author() { return m_author; }
    # read/writable property with input validation
    int rating() { return m_rating; }
    def setRating(rating):

        m_rating = qBound(0, rating, 5)

# private
    m_title = QString()
    m_author = QString()
    m_summary = QString()
    m_rating = 0

Using QObject subclasses allows properties to be bindable , or to have change notification signals. However, using QObject instances for items has significant memory overhead.

Using Qt gadgets or objects is more convenient and can be more flexible than implementing the tuple protocol. Those types are also directly accessible from within QML. However, the access through the property system comes with some runtime overhead. For performance critical models, consider implementing the tuple protocol for compile-time generation of the access code.

Multi-role items

The type of the items that the implementations of data() , setData() , clearItemData() etc. operate on can be the same across the entire model - like in the gridOfNumbers example above. But the range can also have different item types for different columns, like in the numberNames case.

By default, the value gets used for the DisplayRole and EditRole roles. Most views expect the value to be convertible to and from a QString (but a custom delegate might provide more flexibility).

Associative containers with multiple roles

If the item is an associative container that uses int, ItemDataRole , or QString as the key type, and QVariant as the mapped type, then QRangeModel interprets that container as the storage of the data for multiple roles. The data() and setData() functions return and modify the mapped value in the container, and setItemData() modifies all provided values, itemData() returns all stored values, and clearItemData() clears the entire container.

    ColorEntry = QMap<Qt.ItemDataRole, QVariant>()
    colorNames = QColor.colorNames()
colors = QList()
    colors.reserve(colorNames.size())
    for name in colorNames:
        color = QColor.fromString(name)
        colors << ColorEntry{{Qt.ItemDataRole.DisplayRole, name},
                            {Qt.DecorationRole, color},
                            {Qt.ToolTipRole, color.name()}}

    colorModel = QRangeModel(colors)
    list = QListView()
    list.setModel(colorModel)

The most efficient data type to use as the key is ItemDataRole or int. When using int, itemData() returns the container as is, and doesn’t have to create a copy of the data.

Gadgets and Objects as multi-role items

Gadgets and QObject types can also be represented as multi-role items. The properties of those items will be used for the role for which the name of a role matches. If all items hold the same type of gadget or QObject , then the roleNames() implementation in QRangeModel will return the list of properties of that type.

class ColorEntry():

    Q_GADGET
    Q_PROPERTY(QString display MEMBER m_colorName)
    Q_PROPERTY(QColor decoration READ decoration)
    Q_PROPERTY(QString toolTip READ toolTip)
# public
    ColorEntry(QString color = {})
    self.m_colorName = color
    {}
    def decoration():

        return QColor.fromString(m_colorName)

    def toolTip():

        return QColor.fromString(m_colorName).name()

# private
    m_colorName = QString()

When used in a table, this is the default representation for gadgets:

colorTable = QList()
    # ...
    colorModel = QRangeModel(colorTable)
    table = QTableView()
    table.setModel(colorModel)

When used in a list, these types are however by default represented as multi-column rows, with each property represented as a separate column. To force a gadget to be represented as a multi-role item in a list, declare the gadget as a multi-role type by specializing QRoleModel::RowOptions, with a static constexpr auto rowCategory member variable set to MultiRoleItem .

class ColorEntry():

    Q_GADGET
    Q_PROPERTY(QString display MEMBER m_colorName)
    Q_PROPERTY(QColor decoration READ decoration)
    Q_PROPERTY(QString toolTip READ toolTip)
# public            ...

template <>
class QRangeModel.RowOptions():

    staticexpr auto rowCategory = QRangeModel.RowCategory.MultiRoleItem

You can also wrap such types into a single-element tuple, turning the list into a table with a single column:

    colorNames = QColor.colorNames()
colors = QList()
    # ...
    colorModel = QRangeModel(colors)
    list = QListView()
    list.setModel(colorModel)

In this case, note that direct access to the elements in the list data needs to use std::get:

firstEntry = std::get<0>(colors.at(0))

or alternatively a structured binding:

auto [firstEntry] = colors.at(0)

Rows as values or pointers

In the examples so far, we have always used QRangeModel with ranges that hold values. QRangeModel can also operate on ranges that hold pointers, including smart pointers. This allows QRangeModel to operate on ranges of polymorph types, such as QObject subclasses.

class Entry(QObject):

    Q_OBJECT
    Q_PROPERTY(QString display READ display WRITE setDisplay NOTIFY displayChanged)
    Q_PROPERTY(QIcon decoration READ decoration WRITE setDecoration NOTIFY decorationChanged)
    Q_PROPERTY(QString toolTip READ toolTip WRITE setToolTip NOTIFY toolTipChanged)
# public
    Entry() = default
    def display():

        return m_display

    def setDisplay(display):

        if m_display == display:
            return
        m_display = display
        displayChanged.emit(m_display)

# signals
    def displayChanged():            ...

std.vector<std.shared_ptr<Entry>> entries = {            ...

model = QRangeModel(std::ref(entries))
listView = QListView()
listView.setModel(model)

As with values, the type of the row defines whether the range is represented as a list, table, or tree. Rows that are QObjects will present each property as a column, unless the RowOptions template is specialized to declare the type as a multi-role item.

template <>
class QRangeModel.RowOptions():

    staticexpr auto rowCategory = QRangeModel.RowCategory.MultiRoleItem
std.vector<std.shared_ptr<Entry>> entries = {
    std.make_shared<Entry>(),            ...

model = QRangeModel(std::ref(entries))

Note

If the range holds raw pointers, then you have to construct QRangeModel from a pointer or reference wrapper of the range. Otherwise the ownership of the data becomes ambiguous, and a copy of the range would still be operating on the same actual row data, resulting in unexpected side effects.

Subclassing QRangeModel

Subclassing QRangeModel makes it possible to add convenient APIs that take the data type and structure of the range into account.

class NumbersModel(QRangeModel):

    std.vector<int> m_numbers
# public
    NumbersModel(std.vector<int> numbers)
        : QRangeModel(std.ref(m_numbers))
        , m_numbers(numbers)

When doing so, add the range as a private member, and call the QRangeModel constructor with a reference wrapper or pointer to that member. This properly encapsulates the data and avoids direct access.

def setNumber(idx, number):

    setData(index(idx, 0), QVariant.fromValue(number))

def number(idx):

    return m_numbers.at(idx)

Add member functions to provide type-safe access to the data, using the QAbstractItemModel API to perform any operation that modifies the range. Read-only access can directly operate on the data structure.

Trees of data

QRangeModel can represent a data structure as a tree model. Such a tree data structure needs to be homomorphic: on all levels of the tree, the list of child rows needs to use the exact same representation as the tree itself. In addition, the row type needs be of a static size: either a gadget or QObject type, or a type that implements the {C++ tuple protocol}.

To represent such data as a tree, QRangeModel has to be able to traverse the data structure: for any given row, the model needs to be able to retrieve the parent row, and the optional span of children. These traversal functions can be provided implicitly through the row type, or through an explicit protocol type.

Implicit tree traversal protocol

class TreeRow():
Tree = std::vector<TreeRow>

The tree itself is a vector of TreeRow values. See Tree Rows as pointers or values for the considerations on whether to use values or pointers of items for the rows.

class TreeRow():

    Q_GADGET
    # properties
    m_parent = TreeRow()
    std.optional<Tree> m_children
# public
    TreeRow() = default
    # rule of 0: copy, move, and destructor implicitly defaulted

The row class can be of any fixed-size type described above: a type that implements the tuple protocol, a gadget, or a QObject . In this example, we use a gadget.

Each row item needs to maintain a pointer to the parent row, as well as an optional range of child rows. That range has to be identical to the range structure used for the tree itself.

Making the row type default constructible is optional, and allows the model to construct new row data elements, for instance in the insertRow() or moveRows() implementations.

# tree traversal protocol implementation
TreeRow parentRow() { return m_parent; }
std.optional<Tree> childRows() { return m_children; }

The tree traversal protocol can then be implemented as member functions of the row data type. A const parentRow() function has to return a pointer to a const row item; and the childRows() function has to return a reference to a const std::optional that can hold the optional child range.

These two functions are sufficient for the model to navigate the tree as a read-only data structure. To allow the user to edit data in a view, and the model to implement mutating model APIs such as insertRows() , removeRows() , and moveRows() , we have to implement additional functions for write-access:

def setParentRow(parent): m_parent = parent
std.optional<Tree> childRows() { return m_children; }

The model calls the setParentRow() function and mutable childRows() overload to move or insert rows into an existing tree branch, and to update the parent pointer should the old value have become invalid. The non-const overload of childRows() provides in addition write-access to the row data.

Note

The model performs setting the parent of a row, removing that row from the old parent, and adding it to the list of the new parent’s children, as separate steps. This keeps the protocol interface small.

    ...

# Helper to assembly a tree of rows, not used by QRangeModel
template <typename ...Args>
def addChild(and...args):

    if not m_children:
        m_children.emplace(Tree{})
    auto child = m_children.emplace_back(std.forward<Args>(args)...)
    child.m_parent = self
    return child

The rest of the class implementation is not relevant for the model, but a addChild() helper provides us with a convenient way to construct the initial state of the tree.

tree = {
    {"..."},
    {"..."},
    {"..."},

# each toplevel row has three children
tree[0].addChild("...")
tree[0].addChild("...")
tree[0].addChild("...")
tree[1].addChild("...")
tree[1].addChild("...")
tree[1].addChild("...")
tree[2].addChild("...")
tree[2].addChild("...")
tree[2].addChild("...")

A QRangeModel instantiated with an instance of such a range will represent the data as a tree.

# instantiate the model with a pointer to the tree, not a copy!
model = QRangeModel(tree)
view = QTreeView()
view.setModel(model)

Tree traversal protocol in a separate class

The tree traversal protocol can also be implemented in a separate class.

class TreeTraversal():

    TreeRow newRow() { return TreeRow{}; }
    TreeRow parentRow(TreeRow row) { return row.m_parent; }
    def setParentRow(row, parent): row.m_parent = parent
    std.optional<Tree> childRows(TreeRow row) { return row.m_children; }
    std.optional<Tree> childRows(TreeRow row) { return row.m_children; }

Pass an instance of this protocol implementation to the QRangeModel constructor:

def model(tree,TreeTraversal{}):

Tree Rows as pointers or values

The row type of the data range can be either a value, or a pointer. In the code above we have been using the tree rows as values in a vector, which avoids that we have to deal with explicit memory management. However, a vector as a contiguous block of memory invalidates all iterators and references when it has to reallocate the storage, or when inserting or removing elements. This impacts the pointer to the parent item, which is the location of the parent row within the vector. Making sure that this parent (and QPersistentModelIndex instances referring to items within it) stays valid can incurr substantial performance overhead. The QRangeModel implementation has to assume that all references into the range become invalid when modifying the range.

Alternatively, we can also use a range of row pointers as the tree type:

class TreeRow():
Tree = std::vector<TreeRow *>

In this case, we have to allocate all TreeRow instances explicitly using operator new, and implement the destructor to delete all items in the vector of children.

class TreeRow():

    Q_GADGET
# public
    TreeRow(QString value = {})
    self.m_value = value
    {}
    ~TreeRow()

        if m_children:
            qDeleteAll(m_children)

    # move-only
    TreeRow(TreeRow and) = default
    TreeRow operator=(TreeRow and) = default
    # helper to populate
    template <typename ...Args>
    def addChild(and...args):

        if not m_children:
            m_children.emplace(Tree{})
        child = m_children.emplace_back(TreeRow(std::forward<Args>(args)...))
        child.m_parent = self
        return child

# private
    struct = friend()
    m_value = QString()
    std.optional<Tree> m_children
    m_parent = None
tree = {
    TreeRow("1"),
    TreeRow("2"),
    TreeRow("3"),
    TreeRow("4"),

tree[0].addChild("1.1")
tree[1].addChild("2.1")
tree[2].addChild("3.1").addChild("3.1.1")
tree[3].addChild("4.1")

Before we can construct a model that represents this data as a tree, we need to also implement the tree traversal protocol.

class TreeTraversal():

    TreeRow newRow() { return TreeRow(); }
    def deleteRow(row): delete row
    TreeRow parentRow(TreeRow row) { return row.m_parent; }
    def setParentRow(row, parent): row.m_parent = parent
    std.optional<Tree> childRows(TreeRow row) { return row.m_children; }
    std.optional<Tree> childRows(TreeRow row) { return row.m_children; }

An explicit protocol implementation for mutable trees of pointers has to provide two additional member functions, newRow() and deleteRow(RowType *).

if __name__ == "__main__":

    app = QApplication([])
    tree = make_tree_of_pointers()
    def model(std.move(tree),TreeTraversal{}):
    treeView = QTreeView()
    treeView.setModel(model)
    treeView.show()
    sys.exit(app.exec())

The model will call those functions when creating new rows in insertRows() , and when removing rows in removeRows() . In addition, if the model has ownership of the data, then it will also delete all top-level rows upon destruction. Note how in this example, we move the tree into the model, so we must no longer perform any operations on it. QRangeModel , when constructed by moving tree-data with row-pointers into it, will take ownership of the data, and delete the row pointers in it’s destructor.

Using pointers as rows comes with some memory allocation and management overhead. However, the references to the row items remain stable, even when they are moved around in the range, or when the range reallocates. This can significantly reduce the cost of making modifications to the model’s structure when using insertRows() , removeRows() , or moveRows() .

Each choice has different performance and memory overhead trade-offs. The best option depends on the exact use case and data structure used.

The C++ tuple protocol

As seen in the numberNames example above, the row type can be a tuple, and in fact any type that implements the tuple protocol. This protocol is implemented by specializing std::tuple_size and std::tuple_element, and overloading the unqualified get function. Do so for your custom row type to make existing structured data available to the model/view framework in Qt.

class Book():

    title = QString()
    author = QString()
    summary = QString()
    rating = 0
    template <size_t I, typename T>
        requires ((I <= 3) and std.is_same_v<std.remove_cvref_t<T>, Book>)
    def decltype(andbook):

        ifexpr (I == 0)
            def as_const(self, book.title):
        else ifexpr (I == 1)
            def as_const(self, book.author):
        else ifexpr (I == 2)
            return std.forward_like<T>(book.summary)
        else ifexpr (I == 3)
            return std.forward_like<T>(book.rating)


std = {
    template <> struct tuple_size<Book> : std.integral_constant<size_t, 4> {}
    template <size_t I> struct tuple_element<I, Book>
    { using type = decltype(get<I>(std.declval<Book>())); }

In the above implementation, the title and author values of the Book type are returned as const, so the model flags items in those two columns as read-only. The user won’t be able to trigger editing, and setData() does nothing and returns false. For summary and rating the implementation returns the same value category as the book, so when get is called with a mutable reference to a Book, then it will return a mutable reference of the respective variable. The model makes those columns editable, both for the user and for programmatic access.

Note

The implementation of get above requires C++23.

See also

Model/View Programming

class RowCategory

This enum describes how QRangeModel should present the elements of the range it was constructed with.

Constant

Description

QRangeModel.RowCategory.Default

QRangeModel decides how to present the rows.

QRangeModel.RowCategory.MultiRoleItem

QRangeModel will present items with a meta object as multi-role items, also when used in a one-dimensional range.

Specialize the RowOptions template for your type, and add a public member variable static constexpr auto rowCategory with one of the values from this enum.

See also

RowOptions

Note

Properties can be used directly when from __feature__ import true_property is used or via accessor functions otherwise.

property roleNamesᅟ: Dictionary with keys of type .int and values of type QByteArray.

This property holds the role names for the model..

If all columns in the range are of the same type, and if that type provides a meta object (i.e., it is a gadget, or a QObject subclass), then this property holds the names of the properties of that type, mapped to values of ItemDataRole values from UserRole and up. In addition, a role “modelData” provides access to the gadget or QObject instance.

Override this default behavior by setting this property explicitly to a non- empty mapping. Setting this property to an empty mapping, or using resetRoleNames(), restores the default behavior.

See also

roleNames()

Access functions:
__init__(data[, parent=None])
Parameters:
  • dataPyArrayObject

  • parentQObject

The function takes one-dimensional or two-dimensional numpy arrays of various integer or float types to populate an editable QRangeModel.

__init__(list[, parent=None])
Parameters:
  • listPySequence

  • parentQObject

The function takes a sequence of of data to populate a read-only QRangeModel.

resetRoleNames()

Reset function of property roleNamesᅟ .

roleNamesChanged()

Notification signal of property roleNamesᅟ .

setRoleNames(names)
Parameters:

names – Dictionary with keys of type .int and values of type QByteArray.

See also

roleNames()

Setter of property roleNamesᅟ .