PySide6.QtCore.QRangeModel¶
- class QRangeModel¶
QRangeModel
implementsQAbstractItemModel
for any C++ range. More…Added in version 6.10.
Synopsis¶
Properties¶
roleNamesᅟ
- The role names for the model
Methods¶
def
__init__()
def
resetRoleNames()
def
setRoleNames()
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
andstd::end
are implemented, and for which the returned iterator type satisfiesstd::forward_iterator
. Certain model operations will perform better ifstd::size
is available, and if the iterator satisfiesstd::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 assetData()
orinsertRows()
, 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 asinsertRows()
orremoveColumns()
, use standard C++ container APIsresize()
,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 returnfalse
. In the example usingstd::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 usingsetData()
, 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, implementthe 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 viainsertColumns()
andremoveColumns()
. 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 aQObject
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, usingQObject
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 thegridOfNumbers
example above. But the range can also have different item types for different columns, like in thenumberNames
case.By default, the value gets used for the
DisplayRole
andEditRole
roles. Most views expect the value to beconvertible 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
, orQString
as the key type, andQVariant
as the mapped type, thenQRangeModel
interprets that container as the storage of the data for multiple roles. Thedata()
andsetData()
functions return and modify the mapped value in the container, andsetItemData()
modifies all provided values,itemData()
returns all stored values, andclearItemData()
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
orint
. When usingint
,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 thename of a role
matches. If all items hold the same type of gadget orQObject
, then theroleNames()
implementation inQRangeModel
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 toMultiRoleItem
.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 allowsQRangeModel
to operate on ranges of polymorph types, such asQObject
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 orQObject
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. SeeTree 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()
ormoveRows()
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 thechildRows()
function has to return a reference to a conststd::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()
, andmoveRows()
, 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 mutablechildRows()
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 ofchildRows()
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. TheQRangeModel
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 todelete
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()
anddeleteRow(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 inremoveRows()
. 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()
, ormoveRows()
.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 specializingstd::tuple_size
andstd::tuple_element
, and overloading the unqualifiedget
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
andauthor
values of theBook
type are returned asconst
, so the model flags items in those two columns as read-only. The user won’t be able to trigger editing, andsetData()
does nothing and returns false. Forsummary
andrating
the implementation returns the same value category as the book, so whenget
is called with a mutable reference to aBook
, 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 variablestatic 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 ofItemDataRole
values fromUserRole
and up. In addition, a role “modelData” provides access to the gadget orQObject
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
- Access functions:
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:
list –
PySequence
parent –
QObject
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ᅟ
.