Why QList is not working as model to QML GridView?

user13518368

I have problem setting the model to GridView in QML from C++ side. From the documentation about setting Model to GridView in qml it says:

If a C++ model class is used, it must be a subclass of QAbstractItemModel or a simple list.

In my case my data is numbers in matrix (9x9), so I thought easiest way would be using simple list of integers as model in my QML GridView. My QML GridView is:

GridView
{
    id: gridView
    width: root.gridSize
    height: root.gridSize
    Layout.alignment: Qt.AlignHCenter
    model: gridModel
    delegate: Text { text: modelData }
}

And in main.cpp for test I tried this way:

QList<int> test;
test << 1 << 2 << 3 << 4 << 5 << 6 << 7 << 11;
engine.rootContext()->setContextProperty("gridModel", QVariant::fromValue(test));

And this is not working, and data is not displayed in qml. Also if I try QList<QString> data is not displayed in QML.

But if I try with using QStringList like this, it is working:

QStringList test;
test << "1" << "2" << "3" << "4" << "5" << "6" << "7" << "11";
engine.rootContext()->setContextProperty("gridModel", QVariant::fromValue(test));

What I am doing wrong? And why QStringList works but QList<QString> is not working? Since QStringList inherits from QList, does it mean that it should be the same like QList<QString>? My goal is to use list of integers as model to the gridview but this confused me with the strings too.

eyllanesc

One possible solution is to use QVariantList:

QVariantList test;
test << 1 << 2 << 3 << 4 << 5 << 6 << 7 << 11;
engine.rootContext()->setContextProperty("gridModel", test);

On the other hand, the conversion of QList<int> and QList<QString> to the QML Array in a transparent way is valid, that can be verified because the elements can be accessed using [] in addition to the fact that the object has the length attribute.

The problem seems to be that the views only support the classes that it inherits from QAbstractItemModel, QStringList, QVariantList, and numbers, and not the other items.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related