Model in ListView: C++ to QML



  • @
    import QtQuick 1.0

    Rectangle {
    width: 300; height: 40

    Component {
        id: delegate_grafica
        Rectangle {
            width: parent.parent.width; height: 70; color: "salmon"
            radius: 5
            Text { text: title; font.bold: true }
            Text { text: info }//see Biglietto
        }
    }
    
        ListView {
            id: vistaDellaLista; anchors.fill: parent
            model: //as list model...boh, what should i write?
            delegate: delegate_grafica
            spacing: 4;
        }
    

    }
    @

    @
    #include "biglietto.h"

    Biglietto::Biglietto(QString newtitle, QString newinfo)
    {
    QString title = newtitle;
    QString info = newinfo;
    }
    @

    with CPP file, i would to pass the model list to QML, so if i have for example this:
    @
    QList<Biglietto*> list;
    list.append(new Biglietto("Title 1","info 1"));
    list.append(new Biglietto("title 2","info 2")); //list.name = model_list.... how to do this?
    @
    ...so i want this code is the same of this:
    @
    ListModel {
    id: model_list
    ListElement { title: "Title 1"; info: "info 1" }
    ListElement { title: "title 2"; info: "info 2" }
    }
    @



  • You should derive your class from QAbstractListModel.
    Override
    @ QVariant data(const QModelIndex &index, int role) const;@
    Declare enums in your derived class:
    @
    enum ERoles
    {
    TitleRole = Qt::UserRole + 1,
    InfoRole
    }
    @
    In your constructor:
    @
    QHash<int, QByteArray> roles;
    roles[TitleRole] = "title";
    roles[InfoRole] = "info";
    setRoleNames(roles);
    @
    In place where you create your declarative view:
    @
    //QDeclarativeView* declarativeView
    //DerivedModel* derivedModel
    ...
    declarativeView->rootContext()->setContextProperty("yourQMLModelName",derivedModel);
    @



  • thank you for reply. excuse me, what is "derivedmodel"? could you explain the last method please?
    this is my code:
    @
    void Gestore::visualizzaSchermataPrincipale()
    {
    QDeclarativeView* view = new QDeclarativeView;
    QList<Biglietto*> lista = this->makeListWordsAlreadySaved("");
    view->rootContext()->setContextProperty("model_listElements", QVariant::fromValue(lista));
    view->setSource(QUrl::fromLocalFile("qml/WoerterErinnerung/main.qml"));
    QObject *obj_schermataPrincipale = view->rootObject();
    QObject::connect(obj_schermataPrincipale, SIGNAL(signal_visualizzaLeggimi()), this, SLOT(visualizzaLeggimi()));
    QObject::connect(obj_schermataPrincipale, SIGNAL(signal_creaNuovaParola()), this, SLOT(creaNuovaParola()));
    view->show();
    }

    void Gestore::visualizzaSchermataPrincipaleSlot()
    {
    this->visualizzaSchermataPrincipale();
    }

    QList<Biglietto*> Gestore::makeListWordsAlreadySaved(const QString FILTER) //const indicates that FILTER will not be modified in the function
    {
    QList<Biglietto*> lista;//pag 36
    QFile file_contenente_elencoParole("C:/WoerterErinnerung/elencoParoleSalvate.txt");
    if(file_contenente_elencoParole.open(QIODevice::ReadWrite | QIODevice::Append))
    {
    QTextStream leggi_scrivi(&file_contenente_elencoParole);
    leggi_scrivi.setCodec("UTF-8");
    if(FILTER.isEmpty())
    {
    leggi_scrivi.flush();
    while(!leggi_scrivi.atEnd())
    {
    leggi_scrivi.flush();
    QString linea = leggi_scrivi.readLine();
    Biglietto *nuovoBiglietto = new Biglietto(linea.section(" ",-1), linea.section(" ", 5,5), linea.section(" ", 7, 7), linea.section(" ", 1, 1), linea.section(" ",3,3), linea.section(" ", 9, 9));
    lista.append(nuovoBiglietto);
    }
    }
    else
    {
    while(!leggi_scrivi.atEnd())
    {
    leggi_scrivi.flush();
    QString linea = leggi_scrivi.readLine();
    if(linea.contains(FILTER))
    {
    lista.append(new Biglietto(linea.section(" ",-1), linea.section(" ", 5,5), linea.section(" ", 7, 7), linea.section(" ", 1, 1), linea.section(" ",3,3), linea.section(" ", 9, 9)));
    }
    else
    continue;
    }
    }
    file_contenente_elencoParole.close();
    return lista;
    }
    else
    {
    QMessageBox boxInof;
    boxInof.setText("<font size="15">Impossibile aprire lo stream dell' archivio</font>");
    boxInof.exec();
    }
    return lista;
    }
    @

    main.qml
    @
    ...
    ListView { id: list_parolaSalvate; x: 9; y: 130; width: 300; height: 300; delegate: ListDelegate {} model: model_listElements }
    ...
    @

    ListDelegate.qml
    @
    import QtQuick 1.0

    Rectangle
    {
    id: delegate_grafica; width: 300; height: 37; radius: 9; color: get_sfondoBiglietto; border.width: 1; border.color: "yellow"
    Text { id: worttext; x: 18; y: 0; color: "black"; text: get_traduzione; font.bold: true; anchors.verticalCenterOffset: -10;
    anchors.horizontalCenterOffset: -127; font.pixelSize: 15; anchors.centerIn: parent }
    Text { id: deutschbeispiel; x: 18; y: 20; height: 28; color: "black"; text: get_fraseTedesco; font.pixelSize: 12 }
    }
    @

    but there are so a lot error...could you please help me?
    for example, errors are:
    @
    \WoerterErinnerung\gestore.cpp
    mingw32-make[1]: Leaving directory `C:/Users/7-Spode/Documents/Progetti/QT/mobile/WoerterErinnerung-build-simulator'
    In file included from c:\QtSDK\Simulator\Qt\mingw\include\QtDeclarative/qdeclarativecontext.h:48,
    from c:\QtSDK\Simulator\Qt\mingw\include\QtDeclarative/QDeclarativeContext:1,
    from ..\WoerterErinnerung\gestore.cpp:5:
    c:\QtSDK\Simulator\Qt\mingw\include/QtCore/qmetatype.h: In static member function 'static int QMetaTypeId2<T>::qt_metatype_id() [with T = QList<Biglietto*>]':
    c:\QtSDK\Simulator\Qt\mingw\include/QtCore/qmetatype.h:230: instantiated from 'int qMetaTypeId(T*) [with T = QList<Biglietto*>]'
    c:\QtSDK\Simulator\Qt\mingw\include/QtCore/qvariant.h:457: instantiated from 'QVariant qVariantFromValue(const T&) [with T = QList<Biglietto*>]'
    c:\QtSDK\Simulator\Qt\mingw\include/QtCore/qvariant.h:340: instantiated from 'static QVariant QVariant::fromValue(const T&) [with T = QList<Biglietto*>]'
    ..\WoerterErinnerung\gestore.cpp:30: instantiated from here
    c:\QtSDK\Simulator\Qt\mingw\include/QtCore/qmetatype.h:169: error: 'qt_metatype_id' is not a member of 'QMetaTypeId<QList<Biglietto*> >'
    mingw32-make[1]: *** [debug/gestore.o] Error 1
    mingw32-make: *** [debug] Error 2
    The process "C:\QtSDK\mingw\bin\mingw32-make.exe" exited with code 2.
    Error while building project WoerterErinnerung (target: Qt Simulator)
    When executing build step 'Make'
    @



  • model in ListView can be a number model also. Your C++ class can supply a count and then get the required element using a at(), passing the index property.
    @
    MyModelClass:public QObject {
    Q_OBJECT
    public:
    ..
    Q_INVOKABLE int count();
    Q_INVOKABLE QVariant at(int index); // returns data at index from your model
    }
    @

    In QML

    @
    ListView {
    ...
    model: mymodel.count(); // assuming mymodel is injected as context property.
    }

    Component {
    id: delegate
    // access the required data using mymodel.at(index);
    }
    @


Log in to reply
 

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