将二维 QVariantList 从 C++ 传递到 QML
我真的很困惑如何将二维 QVariantList 从 C++ 传递到 QML,我基本上想从 C++ 传递一个值,这与在 QML 中分配它的作用相同:
I am really confused on how to pass a 2-dimensional QVariantList from C++ to QML, I basically want to pass a value from C++ which will do the same as assigning it in QML like this:
property var twoDim: [["1-1", "1-2"],["2-1", "2-2"]]
这样我就可以通过执行以下操作将数组用作 Repeater
元素中的模型: modelData[0]
将返回第一个值数组,以及 modelData[1]
将返回第二个值数组.例如名字和姓氏......
So that I can use the array as a model in a Repeater
element by doing: modelData[0]
which will return 1st array of values, and modelData[1]
which will return 2nd array of values. Names and surnames for example...
请帮忙
推荐答案
首先你可以有一个QVariantList
s的QVariantList
:
Firstly you can have a QVariantList
of QVariantList
s:
// main.cpp
int main( int argc, char* argv[] )
{
QGuiApplication app( argc, argv );
auto myList = QVariantList{};
for ( auto i = 0; i < 2; ++i ) {
myList << QVariant::fromValue(
QVariantList{ QString::number( i + 1 ) + "-1",
QString::number( i + 1 ) + "-2" } );
}
auto view = QQuickView{};
view.rootContext()->setContextProperty( "myList", myList );
view.setSource( QUrl{ QStringLiteral{ "qrc:/QmlCppTest.qml" } } );
view.show();
return app.exec();
}
// QmlCppTest.qml
import QtQuick 2.3
Item {
property var listOfLists: myList
Component.onCompleted: {
for ( var i = 0; i < listOfLists.length; ++i ) {
for ( var j = 0; j < listOfLists[i].length; ++j ) {
print( i, j, listOfLists[i][j] );
}
}
}
}
结果:
qml: 0 0 1-1
qml: 0 1 1-2
qml: 1 0 2-1
qml: 1 1 2-2
但正如我在评论中所说,如果您的第一个维度代表一个实体,而第二个维度代表该实体的属性,则出于性能和维护原因的更好方法是使用 QAbstractItemModel
(或其中一个是更具体的派生类).
But like I said in my comment, if your first dimension represents an entity, and the second dimension represents properties of that entity, the superior approach for performance and maintenance reasons is to use QAbstractItemModel
(or one of it's more specific derived classes).
Qt 的文档中有很多关于 MVC 编程的内容,您应该花一些时间来学习该主题,因为它是 Qt 大部分内容的基础.
Qt's documentation has lots of stuff on MVC programming, you should take some time to learn the subject as it underpins much of Qt.
相关文章