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

It is not clear enough how beginMoveRows works



  • I have a TableView 2.0 in QML and a model derived from QAbstractTableModel in C++ code.

    The model is based on some C++ container of objects, for simplicity let's say it is std::vector<MyObject>, method DoSomeUpdate() switches the elements 0 and 1 places:

        class TableModel : public QAbstractTableModel
        {
        public:
    
            //The implementation of QAbstractTableModel's virtual methods.
    
            int rowCount(const QModelIndex & = QModelIndex()) const override
            {
                return static_cast<int>(m_v.size());
            }
    
            int columnCount(const QModelIndex & = QModelIndex()) const override
            {
                return static_cast<int>(m_cols.size());
            }
    
            QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
            
            QHash<int, QByteArray> roleNames() const override
    
            //My custom method that updates my data and moves the rows.
    
            void DoSomeUpdate()
            {
                bool begun = beginMoveRows(QModelIndex(), 0, 0, QModelIndex(), 1);
                //begun is false at this point, but it is true if the last parameter is 2
                std::swap(m_v[0],m_v[1]);
                endMoveRows();
            }
    
        private:
            
            std::vector<MyObject> m_v;
        };
    

    what parameters should I pass to beginMoveRows to reflect these changes?

    Passing 1 as the last parameter value (as in the code above) is not correct, because there is the following in the docs:

    Note that if sourceParent and destinationParent are the same, you must ensure that the destinationChild is not within the range of sourceFirst and sourceLast + 1.


  • Moderators

    @Dmitriano said in It is not clear enough how beginMoveRows works:

    what parameters should I pass to beginMoveRows to reflect these changes?

    QModelIndex(), 0, 0, QModelIndex(), 2)

    Destination index (last parameter) is specified on model state before the move and points to an item immediately after the index you want to move to. So you want to move item from index 0 to 1 - that means you want your item to be placed before index 2, and that is your parameter value.


  • Moderators

    @Dmitriano said in It is not clear enough how beginMoveRows works:

    what parameters should I pass to beginMoveRows to reflect these changes?

    QModelIndex(), 0, 0, QModelIndex(), 2)

    Destination index (last parameter) is specified on model state before the move and points to an item immediately after the index you want to move to. So you want to move item from index 0 to 1 - that means you want your item to be placed before index 2, and that is your parameter value.


Log in to reply