5

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

enisdenjo
  • 706
  • 9
  • 21
  • Doesn't a `QVariantList` of `QVariantList`s work? Though I should state that stuff like this is much better done through `QAbstractItemModel` from a maintenance and performance point of view. – cmannett85 May 31 '15 at 18:11
  • No, QVariantList of QVariantList does not work, if I append a QVariantList to another QVariantList it just inserts the value in a single array. – enisdenjo May 31 '15 at 18:20
  • I'm a bit new to QML @cmannett85, if you could explain how can I do this using QAbstractItemModel, I would be really gratefull! – enisdenjo May 31 '15 at 18:21

1 Answers1

7

Firstly you can have a QVariantList of QVariantLists:

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

cmannett85
  • 21,725
  • 8
  • 76
  • 119