Click on an element in GridView and invoke a function



  • Hi everyone,
    I have a class (PLModel) subclassing QAbstractItemModel and passed to a QML GridView through the context. The display works fine. The problem is that i want to be able to click on one of those item and invoke a function that acts differently according to the element that has been clicked.
    Here is the code i've come up with so far :

    plmodel.hpp (simplified)

    class PLModel : public QAbstractItemModel
    {
    public :
        // Constructor
        PLModel()
    
       // The functions to subclass QAbstractItemModel
       // index, parent, rowCount, columnCount, data, hasChildren, setData, flags, roleNames
    
       // The method I want to invoke
       Q_INVOKABLE virtual void activateItem( const QModelIndex &index ) Q_DECL_OVERRIDE;
    
        // Other irrelevant stuff
        ...
    };
    

    plmodel.cpp (simplified)

    PLModel::PLModel() { }
    // The imlementation of the functions to subclass QAbstractItemModel
    
    // The method I want to invoke
    void PLModel::activateItem( const QModelIndex &index )
    {
        // For debug
        log_debug (index.row())
        log_debug (index.column())
    
        // Do some other stuff according to the selected item
        // item = getItem ( index )
        ...
    }
    

    ui.qml

    import QtQuick 2.0
    
    Item {
        width: 1000
        height: 1000
    
        GridView {
            id: gridView
            anchors.fill: parent
            cellWidth: 150
            cellHeight: 150
            model: m        // This variable comes from context (= instance of PLModel)
            delegate: Item {
                x: 5
                height: 50
                Image {
                    anchors.horizontalCenter: parent.horizontalCenter
                    id: image
                    width: 100
                    height: 100
                    source: model.image
                    MouseArea {
                        anchors.fill: image
                        onClicked: m.displayInfo(index)   // Where i call the function
                    }
                }
            }
    
        }
    }
    

    Then when i click on an element, the function is called correctly but the 'index' is not correct : index.row = -1 & index.column = -1 (not matter which element i pick). Thus i can't decide what to do because i don't know which element was clicked. I don't understand why i get this index. Am i doing something wrong ? Is there another way to do what i want to do ?

    Thx,
    MoaMoaK


  • Moderators

    Please do not double-post. I'm closing this one.


Log in to reply
 

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