Model支持插入和删除行,需要自己添加插入和删除的函数,并且在插入函数中(插入数据前)调用
void QAbstractItemModel::beginInsertRows(const QModelIndex &parent, int first, int last)
插入数据完成后,调用
void QAbstractItemModel::endInsertRows();
类似地,在删除开始前调用:
void QAbstractItemModel::beginRemoveRows(const QModelIndex &parent, int first, int last)
删除完成后调用:
endRemoveRows();
在stringlistmodel.h文件中:
#ifndef STRINGLISTMODEL_H
#define STRINGLISTMODEL_H
#include <QAbstractListModel>
#include <QStringList>
class MyStringListModel : public QAbstractListModel
{
Q_OBJECT
public:
enum {
DescriptionRole = Qt::UserRole,
};
explicit MyStringListModel(QObject *parent = nullptr);
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role) const override;
virtual QHash<int, QByteArray> roleNames() const override;
Qt::ItemFlags flags(const QModelIndex &index) const override;
bool setData(const QModelIndex &index, const QVariant &value, int role) override;
bool insertRows(int position, int rows, const QModelIndex &parent = QModelIndex()) override;
bool removeRows(int position, int rows, const QModelIndex &parent = QModelIndex()) overr