Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

[SOLVED] Some advice on how to pass a modified role value in the ListView to its listmodel?



  • In my qml project, I have created a custom listmodel by subclassing QAbstractListModel, and I use the PictureModel in a ListView. The ListView contains a Textedit element to display the 'comments' role. I am wondering about that when modifying the comments role value, how to pass the value to its model item.
    Any advice will be appreciated!

    here is the header file:

    @class PictureModel : public QAbstractListModel
    {
    Q_OBJECT

    public:
    enum Roles{
    nameRole = Qt::UserRole + 1,
    CommentsRole
    };

    PictureModel(QObject *parent = 0);
    Qt::ItemFlags flags(const QModelIndex &index) const;
    
    void addPicture(const Picture &picture);
    int rowCount(const QModelIndex &parent = QModelIndex()) const;
    QVariant data(const QModelIndex &index, int role=Qt::DisplayRole) const;
    
    bool setData(const QModelIndex &index, const QVariant &value,
                 int role = Qt::EditRole);
    bool insertRows(int row, int count, const QModelIndex &parent);
    bool removeRows(int row, int count, const QModelIndex &parent);
    

    private:
    QList<Picture> m_pictures;
    };

    @
    here is the part of cpp file:

    @bool PictureModel::setData(const QModelIndex &index, const QVariant &value, int role)
    {
    if(index.isValid()&&role == Qt::EditRole){
    m_pictures.replace(index.row(), value.value<Picture>());
    emit dataChanged(index,index);
    return true;
    }

    return false;
    

    }@

    here is the delegate of the ListView object.
    @
    Component{
    id:listdelegate
    Rectangle{
    id:single
    .............................
    TextEdit {

            id:edit
            width: parent.width
            text: comments
            font.pointSize: 18
            color: "black"
            opacity: 0
            focus: true
            wrapMode :TextEdit.Wrap
        }
    

    .............................
    }
    @



  • add a Q_INVOKABLE function in your model so that you can call it from qml. I think about something like this :
    @
    Q_INVOKABLE void editComments(int listIndex, const QVariant &comments)
    {
    QModelIndex qModelIndex = index(listIndex, 0);
    bool result = setData(qModelIndex, comments, CommentsRole);
    ...
    }
    @



  • I got it, thanks a lot!


Log in to reply