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

how to delete single item from QAbstractTableModel?



  • I am trying to remove a single row and have overridden removeRow() in MyModel.

    class MyModel : public QAbstractTableModel
    {
        QList<MyObject> objects;
    
        public:
            // ...
        
            bool removeRow(int row, const QModelIndex &parent = QModelIndex());
    };
    

    The QAbstractItemModel::removeRow(...) docs say this.

    This is a convenience function that calls removeRows(). 
    

    And so in removeRow() I have the following, but I'm not sure how this should work. Do I have to call removeRows()?

    bool MyModel::removeRow(int row, const QModelIndex &parent)
    {
        beginRemoveRows(parent, first, row); ????
    
        objects.removeAt(row);
    
        endRemoveRows();
    
        return true;
    }


  • In beginRemoveRows function second and third argument should be same, as it's deleting single row.

    beginRemoveRows(parent, row, row);
    

    Application should call removeRow function whenever the particular row to be deleted.
    Refer addressbook program provided in the Qt Examples



  • Override QAbstractItemModel::removeRows rather than QAbstractItemModel::removeRow.
    The function signatures are:

    virtual bool removeRows(int row, int count, const QModelIndex &parent);
    inline bool removeRow(int row, const QModelIndex &parent);
    

    Note that removeRows is virtual, but removeRow is inline.



  • @jeremy_k
    I guess that is the case so that you are free to write your own removeRows() to remove multiple rows in a more efficient fashion than calling removeRow() multiple times, if that suits your impementation?



  • I would phrase it must rather than are free to if either removeRow or removeRows are used via a QAbstractItemModel pointer.

    Otherwise:

    inline bool QAbstractItemModel::removeRow(int arow, const QModelIndex &aparent)
    { return removeRows(arow, 1, aparent); }
    

    Which leads to:

    bool QAbstractItemModel::removeRows(int, int, const QModelIndex &)
    {
        return false;
    }
    


  • @jeremy_k
    Yes indeed! I didn't look, I had assumed removeRows() called removeRow() repeatedly, when in fact it is removeRow() which calls removeRows() once!



  • I noticed you guys didn't write

    beginRemoveRows(...);
    // ...
    endRemoveRows();
    

    Are these not necessary within the removeRow(s) calls?



  • @johnby said in how to delete single item from QAbstractTableModel?:

    I noticed you guys didn't write

    beginRemoveRows(...);
    // ...
    endRemoveRows();
    

    Are these not necessary within the removeRow(s) calls?

    They are necessary, and they should be used in the implementation of removeRows().


Log in to reply