QRangeModel Class

QRangeModel implements QAbstractItemModel for any C++ range. More...

Header: #include <QRangeModel>
CMake: find_package(Qt6 REQUIRED COMPONENTS Core)
target_link_libraries(mytarget PRIVATE Qt6::Core)
qmake: QT += core
Since: Qt 6.10
Inherits: QAbstractItemModel

Note: All functions in this class are reentrant.

Public Types

(since 6.10) struct RowOptions
enum class RowCategory { Default, MultiRoleItem }

Properties

Public Functions

QRangeModel(Range &&range, QObject *parent = nullptr)
QRangeModel(Range &&range, Protocol &&protocol, QObject *parent = nullptr)
virtual ~QRangeModel() override
void resetRoleNames()
void setRoleNames(const QHash<int, QByteArray> &names)

Reimplemented Public Functions

virtual QModelIndex buddy(const QModelIndex &index) const override
virtual bool canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const override
virtual bool canFetchMore(const QModelIndex &parent) const override
virtual bool clearItemData(const QModelIndex &index) override
virtual int columnCount(const QModelIndex &parent = {}) const override
virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override
virtual bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) override
virtual void fetchMore(const QModelIndex &parent) override
virtual Qt::ItemFlags flags(const QModelIndex &index) const override
virtual bool hasChildren(const QModelIndex &parent = QModelIndex()) const override
virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override
virtual QModelIndex index(int row, int column, const QModelIndex &parent = {}) const override
virtual bool insertColumns(int column, int count, const QModelIndex &parent = {}) override
virtual bool insertRows(int row, int count, const QModelIndex &parent = {}) override
virtual QMap<int, QVariant> itemData(const QModelIndex &index) const override
virtual QModelIndexList match(const QModelIndex &start, int role, const QVariant &value, int hits, Qt::MatchFlags flags) const override
virtual QMimeData *mimeData(const QModelIndexList &indexes) const override
virtual QStringList mimeTypes() const override
virtual bool moveColumns(const QModelIndex &sourceParent, int sourceColumn, int count, const QModelIndex &destinationParent, int destinationColumn) override
virtual bool moveRows(const QModelIndex &sourceParent, int sourceRow, int count, const QModelIndex &destinationParent, int destinationRow) override
virtual void multiData(const QModelIndex &index, QModelRoleDataSpan roleDataSpan) const override
virtual QModelIndex parent(const QModelIndex &child) const override
virtual bool removeColumns(int column, int count, const QModelIndex &parent = {}) override
virtual bool removeRows(int row, int count, const QModelIndex &parent = {}) override
virtual QHash<int, QByteArray> roleNames() const override
virtual int rowCount(const QModelIndex &parent = {}) const override
virtual bool setData(const QModelIndex &index, const QVariant &data, int role = Qt::EditRole) override
virtual bool setHeaderData(int section, Qt::Orientation orientation, const QVariant &data, int role = Qt::EditRole) override
virtual bool setItemData(const QModelIndex &index, const QMap<int, QVariant> &data) override
virtual QModelIndex sibling(int row, int column, const QModelIndex &index) const override
virtual void sort(int column, Qt::SortOrder order = Qt::AscendingOrder) override
virtual QSize span(const QModelIndex &index) const override
virtual Qt::DropActions supportedDragActions() const override
virtual Qt::DropActions supportedDropActions() const override

Signals

Reimplemented Protected Functions

virtual bool event(QEvent *event) override
virtual bool eventFilter(QObject *object, QEvent *event) override

Protected Slots

virtual void resetInternalData() override

Detailed Description

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};
QRangeModel model(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.

QRangeModel model(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:

QRangeModel model(&numbers);

or through a reference wrapper:

QRangeModel model(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.

auto shared_numbers = std::make_shared<std::vector<int>>(numbers);
QRangeModel model(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.

const 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<const 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.

QRangeModel model(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.

QList<int> numbers = {1, 2, 3, 4, 5};
QRangeModel model(numbers); // columnCount() == 1
QListView listView;
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
QTableView tableView;
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.

using TableRow = std::tuple<int, QString>;
QList<TableRow> numberNames = {
    {1, "one"},
    {2, "two"},
    {3, "three"}
};
QRangeModel model(&numberNames); // columnCount() == 2
QTableView tableView;
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(const QString &title, const QString &author);

    // C++ rule of 0: destructor, as well as copy/move operations
    // provided by the compiler.

    // read-only properties
    QString title() const { return m_title; }
    QString author() const { return m_author; }

    // read/writable property with input validation
    int rating() const { return m_rating; }
    void setRating(int rating)
    {
        m_rating = qBound(0, rating, 5);
    }

private:
    QString m_title;
    QString m_author;
    QString m_summary;
    int 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 Qt::DisplayRole and Qt::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, Qt::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.

using ColorEntry = QMap<Qt::ItemDataRole, QVariant>;

const QStringList colorNames = QColor::colorNames();
QList<ColorEntry> colors;
colors.reserve(colorNames.size());
for (const QString &name : colorNames) {
    const QColor color = QColor::fromString(name);
    colors << ColorEntry{{Qt::DisplayRole, name},
                        {Qt::DecorationRole, color},
                        {Qt::ToolTipRole, color.name()}};
}
QRangeModel colorModel(colors);
QListView list;
list.setModel(&colorModel);

The most efficient data type to use as the key is Qt::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(const QString &color = {})
        : m_colorName(color)
    {}

    QColor decoration() const
    {
        return QColor::fromString(m_colorName);
    }
    QString toolTip() const
    {
        return QColor::fromString(m_colorName).name();
    }

private:
    QString m_colorName;
};

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

QList<QList<ColorEntry>> colorTable;

// ...

QRangeModel colorModel(colorTable);
QTableView table;
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 <>
struct QRangeModel::RowOptions<ColorEntry>
{
    static constexpr 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:

const QStringList colorNames = QColor::colorNames();
QList<std::tuple<ColorEntry>> colors;

// ...

QRangeModel colorModel(colors);
QListView list;
list.setModel(&colorModel);

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

ColorEntry 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 : public 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;

    QString display() const
    {
        return m_display;
    }

    void setDisplay(const QString &display)
    {
        if (m_display == display)
            return;
        m_display = display;
        emit displayChanged(m_display);
    }

signals:
    void displayChanged(const QString &);
    ...
};
std::vector<std::shared_ptr<Entry>> entries = {
    ...
};
QRangeModel model(std::ref(entries));
QListView listView;
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 QRangeModel::RowOptions template is specialized to declare the type as a multi-role item.

template <>
struct QRangeModel::RowOptions<Entry>
{
    static constexpr auto rowCategory = QRangeModel::RowCategory::MultiRoleItem;
};
std::vector<std::shared_ptr<Entry>> entries = {
    std::make_shared<Entry>(),
    ...
};

QRangeModel model(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 : public QRangeModel
{
    std::vector<int> m_numbers;

public:
    NumbersModel(const 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.

    void setNumber(int idx, int number)
    {
        setData(index(idx, 0), QVariant::fromValue(number));
    }

    int number(int idx) const
    {
        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;

using 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

    TreeRow *m_parent;
    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
    const TreeRow *parentRow() const { return m_parent; }
    const std::optional<Tree> &childRows() const { 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:

    void setParentRow(TreeRow *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>
    TreeRow &addChild(Args &&...args)
    {
        if (!m_children)
            m_children.emplace(Tree{});
        auto &child = m_children->emplace_back(std::forward<Args>(args)...);
        child.m_parent = this;
        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 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!
QRangeModel model(&tree);
QTreeView view;
view.setModel(&model);

Tree traversal protocol in a separate class

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

struct TreeTraversal
{
    TreeRow newRow() const { return TreeRow{}; }
    const TreeRow *parentRow(const TreeRow &row) const { return row.m_parent; }
    void setParentRow(TreeRow &row, TreeRow *parent) const { row.m_parent = parent; }
    const std::optional<Tree> &childRows(const TreeRow &row) const { return row.m_children; }
    std::optional<Tree> &childRows(TreeRow &row) const { return row.m_children; }
};

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

QRangeModel 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:

struct TreeRow;
using 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.

struct TreeRow
{
    Q_GADGET
public:
    TreeRow(const QString &value = {})
        : m_value(value)
    {}
    ~TreeRow()
    {
        if (m_children)
            qDeleteAll(*m_children);
    }

    // move-only
    TreeRow(TreeRow &&) = default;
    TreeRow &operator=(TreeRow &&) = default;

    // helper to populate
    template <typename ...Args>
    TreeRow *addChild(Args &&...args)
    {
        if (!m_children)
            m_children.emplace(Tree{});
        auto *child = m_children->emplace_back(new TreeRow(std::forward<Args>(args)...));
        child->m_parent = this;
        return child;
    }

private:
    friend struct TreeTraversal;
    QString m_value;
    std::optional<Tree> m_children;
    TreeRow *m_parent = nullptr;
};
Tree tree = {
    new TreeRow("1"),
    new TreeRow("2"),
    new TreeRow("3"),
    new 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.

struct TreeTraversal
{
    TreeRow *newRow() const { return new TreeRow; }
    void deleteRow(TreeRow *row) { delete row; }

    const TreeRow *parentRow(const TreeRow &row) const { return row.m_parent; }
    void setParentRow(TreeRow &row, TreeRow *parent) { row.m_parent = parent; }
    const std::optional<Tree> &childRows(const TreeRow &row) const { 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 *).

int main(int argc, char **argv)
{
    QApplication app(argc, argv);

    Tree tree = make_tree_of_pointers();

    QRangeModel model(std::move(tree), TreeTraversal{});
    QTreeView treeView;
    treeView.setModel(&model);
    treeView.show();

    return 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.

struct Book
{
    QString title;
    QString author;
    QString summary;
    int rating = 0;

    template <size_t I, typename T>
        requires ((I <= 3) && std::is_same_v<std::remove_cvref_t<T>, Book>)
    friend inline decltype(auto) get(T &&book)
    {
        if constexpr (I == 0)
            return std::as_const(book.title);
        else if constexpr (I == 1)
            return std::as_const(book.author);
        else if constexpr (I == 2)
            return std::forward_like<T>(book.summary);
        else if constexpr (I == 3)
            return std::forward_like<T>(book.rating);
    }
};

namespace 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.

Member Type Documentation

enum class QRangeModel::RowCategory

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

ConstantValueDescription
QRangeModel::RowCategory::Default0QRangeModel decides how to present the rows.
QRangeModel::RowCategory::MultiRoleItem1QRangeModel 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.

Property Documentation

roleNames : QHash<int, 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 Qt::ItemDataRole values from Qt::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.

Access functions:

virtual QHash<int, QByteArray> roleNames() const override
void setRoleNames(const QHash<int, QByteArray> &names)
void resetRoleNames()

Notifier signal:

void roleNamesChanged()

See also QAbstractItemModel::roleNames().

Member Function Documentation

[explicit] template <typename Range, typename Protocol, int = true> QRangeModel::QRangeModel(Range &&range, Protocol &&protocol, QObject *parent = nullptr)

[explicit] template <typename Range, int = true> QRangeModel::QRangeModel(Range &&range, QObject *parent = nullptr)

[explicit] template <typename Range, int = true> QRangeModel::QRangeModel(Range &&range, QObject *parent = nullptr)

Constructs a QRangeModel instance that operates on the data in range. The range has to be a sequential range for which std::begin and std::end are available. If protocol is provided, then the model will represent the range as a tree using the protocol implementation. The model instance becomes a child of parent.

The range can be a pointer or reference wrapper, in which case mutating model APIs (such as setData() or insertRow()) will modify the data in the referenced range instance. If range is a value (or moved into the model), then connect to the signals emitted by the model to respond to changes to the data.

QRangeModel will not access the range while being constructed. This makes it legal to pass a pointer or reference to a range object that is not fully constructed yet to this constructor, for example when subclassing QRangeModel.

If the range was moved into the model, then the range and all data in it will be destroyed upon destruction of the model.

Note: While the model does not take ownership of the range object otherwise, you must not modify the range directly once the model has been constructed and and passed on to a view. Such modifications will not emit signals necessary to keep model users (other models or views) synchronized with the model, resulting in inconsistent results, undefined behavior, and crashes.

[override virtual noexcept] QRangeModel::~QRangeModel()

Destroys the QRangeModel.

The range that the model was constructed from is not accessed, and only destroyed if the model was constructed from a moved-in range.

[override virtual] QModelIndex QRangeModel::buddy(const QModelIndex &index) const

Reimplements: QAbstractItemModel::buddy(const QModelIndex &index) const.

[override virtual] bool QRangeModel::canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const

Reimplements: QAbstractItemModel::canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const.

[override virtual] bool QRangeModel::canFetchMore(const QModelIndex &parent) const

Reimplements: QAbstractItemModel::canFetchMore(const QModelIndex &parent) const.

[override virtual] bool QRangeModel::clearItemData(const QModelIndex &index)

Reimplements: QAbstractItemModel::clearItemData(const QModelIndex &index).

Replaces the value stored in the range at index with a default- constructed value.

For models operating on a read-only range, or on a read-only column in a row type that implements the C++ tuple protocol, this implementation returns false immediately.

[override virtual] int QRangeModel::columnCount(const QModelIndex &parent = {}) const

Reimplements: QAbstractItemModel::columnCount(const QModelIndex &parent) const.

Returns the number of columns of the model. This function returns the same value for all parent indexes.

For models operating on a statically sized row type, this returned value is always the same throughout the lifetime of the model. For models operating on dynamically sized row type, the model returns the number of items in the first row, or 0 if the model has no rows.

See also rowCount and insertColumns().

[override virtual] QVariant QRangeModel::data(const QModelIndex &index, int role = Qt::DisplayRole) const

Reimplements: QAbstractItemModel::data(const QModelIndex &index, int role) const.

Returns the data stored under the given role for the value in the range referred to by the index.

If the item type for that index is an associative container that maps from either int, Qt::ItemDataRole, or QString to a QVariant, then the role data is looked up in that container and returned.

If the item is a gadget or QObject, then the implementation returns the value of the item's property matching the role entry in the roleNames() mapping.

Otherwise, the implementation returns a QVariant constructed from the item via QVariant::fromValue() for Qt::DisplayRole or Qt::EditRole. For other roles, the implementation returns an invalid (default-constructed) QVariant.

See also Qt::ItemDataRole, setData(), and headerData().

[override virtual] bool QRangeModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent)

Reimplements: QAbstractItemModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent).

[override virtual protected] bool QRangeModel::event(QEvent *event)

Reimplements: QObject::event(QEvent *e).

[override virtual protected] bool QRangeModel::eventFilter(QObject *object, QEvent *event)

Reimplements: QObject::eventFilter(QObject *watched, QEvent *event).

[override virtual] void QRangeModel::fetchMore(const QModelIndex &parent)

Reimplements: QAbstractItemModel::fetchMore(const QModelIndex &parent).

[override virtual] Qt::ItemFlags QRangeModel::flags(const QModelIndex &index) const

Reimplements: QAbstractItemModel::flags(const QModelIndex &index) const.

Returns the item flags for the given index.

The implementation returns a combination of flags that enables the item (ItemIsEnabled) and allows it to be selected (ItemIsSelectable). For models operating on a range with mutable data, it also sets the flag that allows the item to be editable (ItemIsEditable).

See also Qt::ItemFlags.

[override virtual] bool QRangeModel::hasChildren(const QModelIndex &parent = QModelIndex()) const

Reimplements: QAbstractItemModel::hasChildren(const QModelIndex &parent) const.

[override virtual] QVariant QRangeModel::headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const

Reimplements: QAbstractItemModel::headerData(int section, Qt::Orientation orientation, int role) const.

Returns the data for the given role and section in the header with the specified orientation.

For horizontal headers, the section number corresponds to the column number. Similarly, for vertical headers, the section number corresponds to the row number.

See also Qt::ItemDataRole, setHeaderData(), and QHeaderView.

[override virtual] QModelIndex QRangeModel::index(int row, int column, const QModelIndex &parent = {}) const

Reimplements: QAbstractItemModel::index(int row, int column, const QModelIndex &parent) const.

Returns the index of the model item at row and column in parent.

Passing a valid parent produces an invalid index for models that operate on list and table ranges.

See also parent().

[override virtual] bool QRangeModel::insertColumns(int column, int count, const QModelIndex &parent = {})

Reimplements: QAbstractItemModel::insertColumns(int column, int count, const QModelIndex &parent).

Inserts count empty columns before the item at column in all rows of the range at parent. Returns true if successful; otherwise returns false.

Note: A dynamically sized row type needs to provide a insert(const_iterator, size_t, value_type) member function.

For models operating on a read-only range, or on a range with a statically sized row type (such as a tuple, array, or struct), this implementation does nothing and returns false immediately. This is always the case for tree models.

[override virtual] bool QRangeModel::insertRows(int row, int count, const QModelIndex &parent = {})

Reimplements: QAbstractItemModel::insertRows(int row, int count, const QModelIndex &parent).

Inserts count empty rows before the given row into the range at parent. Returns true if successful; otherwise returns false.

Note: The range needs to be dynamically sized and provide a insert(const_iterator, size_t, value_type) member function.

For models operating on a read-only or statically-sized range (such as an array), this implementation does nothing and returns false immediately.

Note: For ranges with a dynamically sized column type, the column needs to provide a resize(size_t) member function.

[override virtual] QMap<int, QVariant> QRangeModel::itemData(const QModelIndex &index) const

Reimplements: QAbstractItemModel::itemData(const QModelIndex &index) const.

Returns a map with values for all predefined roles in the model for the item at the given index.

If the item type for that index is an associative container that maps from either int, Qt::ItemDataRole, or QString to a QVariant, then the data from that container is returned.

If the item type is a gadget or QObject subclass, then the values of those properties that match a role name are returned.

If the item is not an associative container, gadget, or QObject subclass, then this calls the base class implementation.

See also setItemData(), Qt::ItemDataRole, and data().

[override virtual] QModelIndexList QRangeModel::match(const QModelIndex &start, int role, const QVariant &value, int hits, Qt::MatchFlags flags) const

Reimplements: QAbstractItemModel::match(const QModelIndex &start, int role, const QVariant &value, int hits, Qt::MatchFlags flags) const.

[override virtual] QMimeData *QRangeModel::mimeData(const QModelIndexList &indexes) const

Reimplements: QAbstractItemModel::mimeData(const QModelIndexList &indexes) const.

[override virtual] QStringList QRangeModel::mimeTypes() const

Reimplements: QAbstractItemModel::mimeTypes() const.

[override virtual] bool QRangeModel::moveColumns(const QModelIndex &sourceParent, int sourceColumn, int count, const QModelIndex &destinationParent, int destinationColumn)

Reimplements: QAbstractItemModel::moveColumns(const QModelIndex &sourceParent, int sourceColumn, int count, const QModelIndex &destinationParent, int destinationChild).

Moves count columns starting with the given sourceColumn under parent sourceParent to column destinationColumn under parent destinationParent.

Returns true if the columns were successfully moved; otherwise returns false.

[override virtual] bool QRangeModel::moveRows(const QModelIndex &sourceParent, int sourceRow, int count, const QModelIndex &destinationParent, int destinationRow)

Reimplements: QAbstractItemModel::moveRows(const QModelIndex &sourceParent, int sourceRow, int count, const QModelIndex &destinationParent, int destinationChild).

Moves count rows starting with the given sourceRow under parent sourceParent to row destinationRow under parent destinationParent.

Returns true if the rows were successfully moved; otherwise returns false.

[override virtual] void QRangeModel::multiData(const QModelIndex &index, QModelRoleDataSpan roleDataSpan) const

Reimplements: QAbstractItemModel::multiData(const QModelIndex &index, QModelRoleDataSpan roleDataSpan) const.

[override virtual] QModelIndex QRangeModel::parent(const QModelIndex &child) const

Reimplements: QAbstractItemModel::parent(const QModelIndex &index) const.

Returns the parent of the item at the child index.

This function always produces an invalid index for models that operate on list and table ranges. For models operation on a tree, this function returns the index for the row item returned by the parent() implementation of the tree traversal protocol.

See also index() and hasChildren().

[override virtual] bool QRangeModel::removeColumns(int column, int count, const QModelIndex &parent = {})

Reimplements: QAbstractItemModel::removeColumns(int column, int count, const QModelIndex &parent).

Removes count columns from the item at column on in all rows of the range at parent. Returns true if successful, otherwise returns false.

Note: A dynamically sized row type needs to provide a erase(const_iterator, size_t) member function.

For models operating on a read-only range, or on a range with a statically sized row type (such as a tuple, array, or struct), this implementation does nothing and returns false immediately. This is always the case for tree models.

[override virtual] bool QRangeModel::removeRows(int row, int count, const QModelIndex &parent = {})

Reimplements: QAbstractItemModel::removeRows(int row, int count, const QModelIndex &parent).

Removes count rows from the range at parent, starting with the given row. Returns true if successful, otherwise returns false.

Note: The range needs to be dynamically sized and provide a erase(const_iterator, size_t) member function.

For models operating on a read-only or statically-sized range (such as an array), this implementation does nothing and returns false immediately.

[override virtual protected slot] void QRangeModel::resetInternalData()

Reimplements: QAbstractItemModel::resetInternalData().

[override virtual] QHash<int, QByteArray> QRangeModel::roleNames() const

Reimplements: QAbstractItemModel::roleNames() const.

Note: Overriding this function in a QRangeModel subclass is possible, but might break the behavior of the property.

Note: Getter function for property roleNames.

See also setRoleNames().

[override virtual] int QRangeModel::rowCount(const QModelIndex &parent = {}) const

Reimplements: QAbstractItemModel::rowCount(const QModelIndex &parent) const.

Returns the number of rows under the given parent. This is the number of items in the root range for an invalid parent index.

If the parent index is valid, then this function always returns 0 for models that operate on list and table ranges. For trees, this returns the size of the range returned by the childRows() implementation of the tree traversal protocol.

See also columnCount(), insertRows(), and hasChildren().

[override virtual] bool QRangeModel::setData(const QModelIndex &index, const QVariant &data, int role = Qt::EditRole)

Reimplements: QAbstractItemModel::setData(const QModelIndex &index, const QVariant &value, int role).

Sets the role data for the item at index to data.

If the item type for that index is an associative container that maps from either int, Qt::ItemDataRole, or QString to a QVariant, then data is stored in that container for the key specified by role.

If the item is a gadget or QObject, then data is written to the item's property matching the role entry in the the roleNames() mapping. The function returns true if a property was found and if data stored a value that could be converted to the required type, otherwise returns false.

Otherwise, this implementation assigns the value in data to the item at the index in the range for Qt::DisplayRole and Qt::EditRole, and returns true. For other roles, the implementation returns false.

For models operating on a read-only range, or on a read-only column in a row type that implements the C++ tuple protocol, this implementation returns false immediately.

See also data().

[override virtual] bool QRangeModel::setHeaderData(int section, Qt::Orientation orientation, const QVariant &data, int role = Qt::EditRole)

Reimplements: QAbstractItemModel::setHeaderData(int section, Qt::Orientation orientation, const QVariant &value, int role).

See also headerData().

[override virtual] bool QRangeModel::setItemData(const QModelIndex &index, const QMap<int, QVariant> &data)

Reimplements: QAbstractItemModel::setItemData(const QModelIndex &index, const QMap<int, QVariant> &roles).

If the item type for that index is an associative container that maps from either int or Qt::ItemDataRole to a QVariant, then the entries in data are stored in that container. If the associative container maps from QString to QVariant, then only those values in data are stored for which there is a mapping in the role names table.

If the item type is a gadget or QObject subclass, then those properties that match a role name are set to the corresponding value in data.

Roles for which there is no entry in data are not modified.

For item types that can be copied, this implementation is transactional, and returns true if all the entries from data could be stored. If any entry could not be updated, then the original container is not modified at all, and the function returns false.

If the item is not an associative container, gadget, or QObject subclass, then this calls the base class implementation, which calls setData() for each entry in data.

See also itemData(), setData(), and Qt::ItemDataRole.

[override virtual] QModelIndex QRangeModel::sibling(int row, int column, const QModelIndex &index) const

Reimplements: QAbstractItemModel::sibling(int row, int column, const QModelIndex &index) const.

Returns the sibling at row and column for the item at index, or an invalid QModelIndex if there is no sibling at that location.

This implementation is significantly faster than going through the parent() of the index.

See also index(), QModelIndex::row(), and QModelIndex::column().

[override virtual] void QRangeModel::sort(int column, Qt::SortOrder order = Qt::AscendingOrder)

Reimplements: QAbstractItemModel::sort(int column, Qt::SortOrder order).

[override virtual] QSize QRangeModel::span(const QModelIndex &index) const

Reimplements: QAbstractItemModel::span(const QModelIndex &index) const.

[override virtual] Qt::DropActions QRangeModel::supportedDragActions() const

Reimplements: QAbstractItemModel::supportedDragActions() const.

[override virtual] Qt::DropActions QRangeModel::supportedDropActions() const

Reimplements: QAbstractItemModel::supportedDropActions() const.

© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.