Search code examples
c++listviewqmldatamodel

QML-Listview (Cpp-Model) Details-Dialog


EDIT: 26.08.2014 08:20 - Completely reworked question!

What I want to do is:

  1. Fill a qml-listview with data from a cpp-listmodel (QAbstractListModel).
  2. Open a Dialog that show's more data from the cpp-listmodel by click on a listview-item.

I have two cpp-Classes:

  1. DataModelItem with two attributes (listData (displayed in the listview) and detailsData (displayed in the Dialog))
  2. DataModel which inherits QAbstractListModel with an attribut QList itemList.

DataModel.cpp:

QVariant DataModel::data(const QModelIndex &index, int role) const
{
    DataModelItem *item = m_itemList.at(index.row());
    switch (role) {
    case ListDataRole:
        return QString().sprintf("%.2f", item->listData());
        break;
    case DetailsDataRole:
        return QString().sprintf("%.4f", item->detailsData());
        break;
    default:
        qDebug () << "role not handled";
    }

    return QVariant();
}

What I now wanna do is, to display the listData in the ListView. When I click on one ListItem a dialog should appear with the detailsData.


Solution

  • I figured out, that I can't write model.detailsData in my main application, but just detailsData works (I also tried listview.model.detailsData with no effect). Probably someone know why this does not work.

    Anyway I found a solution.

    Here's the working example:

    main.qml

    import QtQuick 1.1
    
    Rectangle {
        width: 200
        height: 400
    
        ListView {
            id: listView
    
            model: dataModel
            delegate: listDelegate
        }
    
        Component {
            id: listDelegate
    
            Item {
                id: delegateItem
                width: listDataText.width
                height: listDataText.height
                Text {
                    id: listDataText
                    text: listData
                }
    
                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        console.log(detailsData)
                        itemDetails.details = model.detailsData
                        itemDetails.visible = true
                    }
                }
            }
        }
    
        DetailsDialog {
            id: itemDetails
            visible: false
            anchors.centerIn: parent
        }
    }
    

    DetailsDialog.qml

    import QtQuick 1.1
    
    Rectangle {
        property alias details: detailsText.text
        width: 100
        height: 62
    
        Text {
            id: detailsText
    
        }
    }