How to assign the Qlist as model for ListView?



  • Hi,

    I read the values from XML file and store it in the object, and the object stored in the Qlist.This mentioned coded in HomeController.cpp. Now I want to now, how to assign the Qlist to Listview in qml?

    HomeController.h:

    struct PortalMapItemInfo {
    QString pstrTitle;
    QString pstrItemId;
    QString pstrDescription;
    QString pstrCreated;
    };
    
    class HomeController : public QObject
    {
    
    Q_OBJECT
    
    public:
    
    Q_INVOKABLE bool eveReadXML();
    
    }
    

    HomeController.CPP:

    void HomeController::eveReadXML()
    {
    
    //Read the xml Value and load it the object of the class
    PortalMapItemInfo obj;
    
    obj.pstrTitle = strTitle;
    obj.pstrItemId = strItemId;
    obj.pstrDescription = strDescription;
    obj.pstrCreated = strCreated;
    
    QList<PortalMapItemInfo> datalist;
    
    datalist << obj; //Values are properly binded.
    
    }
    

    ListPortalItem.Qml

    ListView {
    id: idListView
    anchors {
    left: parent.left
    leftMargin: 10 * scaleFactor
    right: parent.right
    rightMargin: 10 * scaleFactor
    top: rectangleToolBar.bottom
    topMargin: 10 * scaleFactor
    bottom: rectangleStatusBar.top
    bottomMargin: 10 * scaleFactor
    }
    
    // model:???????????????????????????
    delegate: comsearchDelegate
    spacing: 10 * scaleFactor
    clip: true
    
    
    
    
    
    }
    
    Component {
    id: comsearchDelegate
    
    Row {
    spacing: 10 * scaleFactor
    
    Image {
    id: imageItem
    width: 100 * scaleFactor
    height: 70 * scaleFactor
    source: thumbnailUrl
    }
    
    Column {
    Layout.alignment: Qt.AlignTop
    Text { text: title; font { pixelSize: 14 * scaleFactor; bold: true } }
    
    }
    }
    }
    


  • @Mathan-M

    I have added code wrappers to your post. Please use them. You can introduce them by using the right most button above the edit window.



  • The easy way:
    get rid of PortalMapItemInfo, store the values in 4 different QStringList and use a QStringListModel

    The proper way:
    in HomeController.h add Q_DECLARE_METATYPE(PortalMapItemInfo) http://doc.qt.io/qt-5/qmetatype.html#Q_DECLARE_METATYPE

    Instead of a List store your data in a 1-column QStandardItemModel and expose it via a Q_PRPERTY


Log in to reply