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 and 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. Use QRangeModelAdapter to implicitly construct a model while also having direct, type-safe, and convenient access to the model as a range.

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)

Changes made to the data can be monitored by connecting to 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. Use QRangeModelAdapter to safely interact with the underlying range while keeping the model updated.

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 READ colorName)
    Q_PROPERTY(QColor decoration READ decoration)
    Q_PROPERTY(QString toolTip READ toolTip)
# public
    ColorEntry(QString color = {})
    self.m_colorName = color
    {}
    def colorName():

        return m_colorName

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

Customization by template specialization

QRangeModel declares two nested templates types that you can specialize to override default behavior.

The RowOptions template we have already introduced above is for customizing functionality that is specific to the row-type, such as header data, or that should apply uniformly to all items in a row, such as default flags. The ItemAccess template allows customizing item type specific behavior, such as reading or writing role data.

These two templates always need to be specialized for the underlying type, so even if the range holds rows of type Row as std::unique_ptr<Row>, or items of type Item as std::shared_ptr<Item>, the specialization needs to be for Row and Item.

    template <>
class QRangeModel.ItemAccess():            ...

    std.vector<std.shared_ptr<ColorEntry>> colors
# ...
    model = QRangeModel(colors)

Note

In C++ you should only ever specialize templates for types that you own, and not for standard or Qt types. Create subclasses or aggregates for types you don’t control if you need to customize behavior for those types. Note that a type alias is not a distinct type, and you should not specialize templates for alias types. However, it is allowed to create a specialization of a standard or Qt container with a type that you own, such as a std::vector<MyGadget>.

Row and item specific flags

The default implementation of flags() returns a combination of ItemIsSelectable , ItemIsEnabled , and - except for items at column 0 of a tree model - ItemNeverHasChildren . The ItemIsEditable and ItemIsDropEnabled flags are set for all items in models that are not read-only, and ItemIsDragEnabled is set as long as the model supports at least one mime type .

To customize the default behavior for all items in a row, specialize the RowOptions template. To access per-item flag data, specialize the ItemAccess template. You can do both: RowOptions can set flags that are common for all items in a row, and ItemAccess can set flags for items backed by a specific type.

Drag’n’drop handling

Since Qt 6.12, QRangeModel implements the flags() virtual function to set the ItemIsDragEnabled flag for all valid items in a model, as long as the model supports at least one mime type . This is the default, as QAbstractItemModel provides the Qt-internal “application/x-qabstractitemmodeldatalist” mime type. In addition, the ItemIsDropEnabled flag is set for items in such a model as long as that model is not read-only. This includes the non-existent item at the invalid index, so users can drop data into empty areas of a view to append the data.

Implementing support for additional mime types can be done without subclassing QRangeModel and overriding the respective virtual functions. QRangeModel will detect and use functions in the ItemAccess and RowOptions customization templates to encode rows or items as mime data , and to decode mime data into sequences of rows or items. These customization functions can operate directly on the row and item types, without taking detours through QModelIndex and QVariant .

This way, the code for serializing data can be type-safe, and can stay with the implementation of the type that is used to store the data.

In addition, supportedDragActions() and supportedDropActions() are properties that can be configured for each QRangeModel instance.

Advanced C++ topics

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.

Binary compatibility considerations

QRangeModel is not a template class. Passing QRangeModel instances (by pointer or reference, as with all QObject classes) through library APIs, or storing QRangeModel by value in a public class of a library, is safe.

However, the QRangeModel constructor is a template and inline, and the internal implementation that is specialized on the type of the range the model operates on is instantiated in the constructor. You should not call the constructor in an inline-implementation of a library API. It results in ODR violations, and might break binary compatibility of that library if the Qt version it gets built against is different from the Qt version an application using that library is built against.

New and optimized implementations of virtual functions introduced in later version of Qt might also not be used if QRangeModel detects that the implementation was compiled against an older version of Qt. For instance, the implementations of sort() and match() are new in Qt 6.12, but will not be called by an application that was compiled against Qt 6.11, even if the Qt library used is Qt 6.12. To benefit from such new overrides, recompile your application.

See also

QRangeModelAdapter QAbstractItemModel QStandardItemModelModel/View Programming

class AutoConnectPolicy

This enum defines if and when QRangeModel auto-connects changed-signals for properties to the dataChanged() signal of the model. Only properties that match one of the role names are connected.

Constant

Description

QRangeModel.AutoConnectPolicy.None_

No connections are made automatically.

QRangeModel.AutoConnectPolicy.Full

The signals for all relevant properties are connected automatically, for all QObject items. This includes QObject items that are added to newly inserted rows and columns.

QRangeModel.AutoConnectPolicy.OnRead

Signals for relevant properties are connected the first time the model reads the property.

The memory overhead of making automatic connections can be substantial. A Full auto-connection does not require any book-keeping in addition to the connection itself, but each connection takes memory, and connecting all properties of all objects can be very costly, especially if only a few properties of a subset of objects will ever change.

The OnRead connection policy will not connect to objects or properties that are never read from (for instance, never rendered in a view), but remembering which connections have been made requires some book-keeping overhead, and unpredictable memory growth over time. For instance, scrolling down a long list of items can easily result in thousands of new connections being made.

See also

autoConnectPolicy() roleNames()

Added in version 6.11.

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

class DropOperation

This enum defines how data decoded in a dropMimeData() customization gets written to the model.

Constant

Description

QRangeModel.DropOperation.DontDrop

The data should not be added to the model.

QRangeModel.DropOperation.Automatic

Qt determines how data gets added to the model.

QRangeModel.DropOperation.OverwriteAndIgnore

Overwrite the dropped-on item and following items, and discard any dropped data that doesn’t fit.

QRangeModel.DropOperation.OverwriteAndExtend

Overwrite the dropped-on item and following items, and grow the model to fit all dropped data.

QRangeModel.DropOperation.InsertAsSiblings

Insert all dropped data as siblings of the dropped-on item.

QRangeModel.DropOperation.InsertAsChildren

Insert all dropped data as children of the dropped-on item.

A dropMimeData() customization can return a bool value instead, in which case false maps to the DontDrop value, and true to Automatic.

See also

canDropMimeData() dropMimeData()

Added in version 6.12.

Note

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

property autoConnectPolicyᅟ: QRangeModel.AutoConnectPolicy

This property holds if and when the model auto-connects to property changed notifications..

If QRangeModel operates on a data structure that holds the same type of QObject subclass as its row or item type, then it can automatically connect the properties of the QObjects to the dataChanged() signal. For QObject rows, this is done for each column, mapping to the DisplayRole property. For items, this is done for those properties that match one of the role names .

By default, the value of this property is None , so no such connections are made. Changing the value of this property always breaks all existing connections.

Note

Connections are not broken or created if QObjects in the data structure that QRangeModel operates on are swapped out.

See also

roleNames()

Access functions:
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:
property sortCollatorᅟ: QCollator

This property holds the collator that will be used when sorting the model.

The default value of this property is a QCollator for the C-locale. Sorting will not be locale aware, and case sensitive. Setting a collator will make the sorting locale-aware.

Access functions:
property sortRoleᅟ: int

This property holds the data role used when sorting items..

The default value is DisplayRole .

Access functions:
property supportedDragActionsᅟ: Combination of Qt.DropAction

This property holds the drag-actions supported by this model..

Actions that the model cannot support, such as moving data out of a read-only model, will be removed when setting the actions.

Note

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

See also

supportedDropActions()

Access functions:
property supportedDropActionsᅟ: Combination of Qt.DropAction

This property holds the drop-actions supported by this model..

Read-only models cannot support any drop-actions.

Note

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

See also

supportedDragActions()

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

  • parent – QObject

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.

autoConnectPolicy()
Return type:

AutoConnectPolicy

Getter of property autoConnectPolicyᅟ .

autoConnectPolicyChanged(policy)
Parameters:

policy – AutoConnectPolicy

Notification signal of property autoConnectPolicyᅟ .

resetRoleNames()

Reset function of property roleNamesᅟ .

resetSortCollator()

Reset function of property sortCollatorᅟ .

resetSortRole()

Reset function of property sortRoleᅟ .

resetSupportedDragActions()

Reset function of property supportedDragActionsᅟ .

resetSupportedDropActions()

Reset function of property supportedDropActionsᅟ .

roleNamesChanged()

Notification signal of property roleNamesᅟ .

setAutoConnectPolicy(policy)
Parameters:

policy – AutoConnectPolicy

Setter of property autoConnectPolicyᅟ .

setRoleNames(names)
Parameters:

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

See also

roleNames()

Setter of property roleNamesᅟ .

setSortCollator(collator)
Parameters:

collator – QCollator

See also

sortCollator()

Setter of property sortCollatorᅟ .

setSortRole(role)
Parameters:

role – int

See also

sortRole()

Setter of property sortRoleᅟ .

setSupportedDragActions(actions)
Parameters:

actions – Combination of DropAction

See also

supportedDragActions()

Setter of property supportedDragActionsᅟ .

setSupportedDropActions(actions)
Parameters:

actions – Combination of DropAction

See also

supportedDropActions()

Setter of property supportedDropActionsᅟ .

sortCollator()
Return type:

QCollator

Getter of property sortCollatorᅟ .

sortCollatorChanged(collator)
Parameters:

collator – QCollator

Notification signal of property sortCollatorᅟ .

sortRole()
Return type:

int

See also

setSortRole()

Getter of property sortRoleᅟ .

sortRoleChanged(role)
Parameters:

role – int

Notification signal of property sortRoleᅟ .

supportedDragActionsChanged(actions)
Parameters:

actions – Combination of DropAction

Notification signal of property supportedDragActionsᅟ .

supportedDropActionsChanged(actions)
Parameters:

actions – Combination of DropAction

Notification signal of property supportedDropActionsᅟ .