简体   繁体   English

为什么 QList 不能作为 model 到 QML GridView 工作?

[英]Why QList is not working as model to QML GridView?

I have problem setting the model to GridView in QML from C++ side.我在从 ZF6F87C9FDCF8B3C3F07F93F1EE8712C9 的GridView中将 model 设置为 GridView 时遇到问题。 From the documentation about setting Model to GridView in qml it says:从有关在 qml 中将 Model 设置为 GridView 的文档中说:

If a C++ model class is used, it must be a subclass of QAbstractItemModel or a simple list.如果使用 C++ model class,它必须是 QAbstractItemModel 的子类或简单列表。

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.在我的情况下,我的数据是矩阵(9x9)中的数字,所以我认为最简单的方法是在我的 QML GridView 中使用简单的整数列表作为 model。 My QML GridView is:我的 QML GridView 是:

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:main.cpp中进行测试,我尝试了这种方式:

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.这不起作用,qml 中不显示数据。 Also if I try QList<QString> data is not displayed in QML.此外,如果我尝试QList<QString>数据不会显示在 QML 中。

But if I try with using QStringList like this, it is working:但是,如果我尝试像这样使用QStringList ,它正在工作:

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?为什么QStringList有效但QList<QString>无效? Since QStringList inherits from QList, does it mean that it should be the same like QList<QString> ?由于 QStringList 继承自 QList,是否意味着它应该与QList<QString>相同? My goal is to use list of integers as model to the gridview but this confused me with the strings too.我的目标是使用整数列表作为 model 到 gridview 但这也让我对字符串感到困惑。

One possible solution is to useQVariantList :一种可能的解决方案是使用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.另一方面,以透明方式将QList<int>QList<QString>转换为 QML 数组是有效[] ,因为除了 object 具有length属性。

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.问题似乎是视图只支持它从 QAbstractItemModel、QStringList、QVariantList 和数字继承的类,而不支持其他项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM