How to expose model to QML



  • Hey There, I need to expose model in qml file,

    like

    mail.cpp

    int main(int argc, char *argv[])
    {
    QApplication app(argc, argv);

    QStandardItemModel model(4, 4);
    for (int row = 0; row < 4; ++row) {
        for (int column = 0; column < 4; ++column) {
            QStandardItem *item = new QStandardItem(QString("row %0, column %1").arg(row).arg(column));
            model.setItem(row, column, item);
        }
    }
    MyClass myc(model);
    
    //qDebug()<<"Data from model "<<myc.
    //MyClass myc;
    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    engine.rootContext()->setContextProperty("myc", &myc);
    engine.rootContext()->setContextProperty("datamodel", &model);
    
    
    return app.exec();
    

    -----------------------------main.qml is

    Rectangle {

            id: graphContainer
            visible: false
            x: 0
            y: 200
            width: 630
            height: 443
    
           gradient: Gradient {
                GradientStop {
                    position: 0
                    color: "#ffffff"
                }
    
                GradientStop {
                    position: 1
                    color: "#000000"
                }
            }
    
           Graph
           {
               id:graphChart
               model:datamodel
    
           }
    
        }
    

    but it gives me error


  • Qt Champions 2016

    Hi

    • "but it gives me error"
      Always include the actual error with as much info as possible. :)

  • Moderators

    said in How to expose model to qml:

    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    engine.rootContext()->setContextProperty("myc", &myc);
    engine.rootContext()->setContextProperty("datamodel", &model);

    Perhaps you should try setting model before setting the QML.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.