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"]]
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...
Please help
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] );
}
}
}
}
Results in:
qml: 0 0 1-1
qml: 0 1 1-2
qml: 1 0 2-1
qml: 1 1 2-2
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's documentation has lots of stuff on MVC programming, you should take some time to learn the subject as it underpins much of Qt.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With