Display and refresh a dynamic list on QML



  • Hi all,
    In my application I need to create a dynamic list, I retrieved my data from json and I used QML for views.
    I declare the list in main using setContextProperty as follows:
    int main(int argc, char argv[])
    {
    QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    qputenv("QT_QUICK_CONTROLS_STYLE", "material");
    QGuiApplication app(argc, argv);
    ApplicationUI appui;
    QQmlApplicationEngine engine;
    QQmlContext context = engine.rootContext();
    context->setContextProperty("myApp", &appui);

    //Users list
    QList<User*> listuser;
    listuser=u.getallUser() ;
    UserEntityModel modeluser;
    for(int i =0;i<listuser.size();i++ )
    {
    QString fullname = listuser[i]->fullname();
    QString email= listuser[i]->Email();
    QString grade= listuser[i]->grade();
    QString evaluation = listuser[i]->evaluation();
    QString photo=listuser[i]->photo();
    modeluser.addUserEntity(UserEntity(fullname,email,grade,evaluation,photo));
    }
    context->setContextProperty("userModel", &modeluser);
    engine.load(QUrl(QStringLiteral("qrc:/qml/main.qml")));
    return app.exec();
    }
    In QML I retrieve my list as follows:
    ListView {
    id: listViewuser
    anchors.bottomMargin: -3
    anchors.leftMargin: -18
    anchors.topMargin: -3
    anchors.rightMargin: 5
    focus: true
    clip: true
    anchors.fill: parent
    model:userModel
    delegate: userComponent
    section.property: "sortGroup"
    section.criteria: ViewSection.FullString
    section.delegate: stateChanged
    }
    But when I add a new object, I need to close the application and start the new main so that the list will be refreshed in the graphical interface (QML).
    While I want to refreshethe list automatically without closing the application.
    I try to declare the list in a different class than the main, but in QML I got this error: "userModel undefined" .



  • @jiji What is this UserEntityModel?



  • Hello,
    Could you use the code syntax ?

    Something like :

    Rectangle {
        color : "red
    }
    




  • @jiji Do you inform the ListView that the data changed? You have to send a signal, for example the dataChanged signal. I assume, since your ListView shows data that you are already using on of Qt's models.

    You can look up dataChanged in my post here:
    https://forum.qt.io/topic/78802/datachange-signal-ignored-by-gridview/2

    And in general you can read how data can be set in a model here:
    http://doc.qt.io/qt-5/qabstractitemmodel.html#setData

    Although, you don't have to use setData, but you have to send the signal.



  • Hello, dear developer! Please, use the "forceLayout()" method on your ListView. It automatically updates it in order to match the datas of the model.

    Hope it helped!


Log in to reply
 

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