Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing 2-dimensional QVariantList from C++ to QML

Tags:

c++

qt

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"]]

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

like image 823
enisdenjo Avatar asked May 31 '15 17:05

enisdenjo


Video Answer


1 Answers

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.

like image 121
cmannett85 Avatar answered Nov 03 '22 01:11

cmannett85