前面的例子已经比较清楚的给出了自定义model的方法,就是要覆盖我们所需要的那几个函数就可以了。但是,前面的例子仅仅是简单的展示数据,也就是说数据时只读的。那么,如何能做到读写数据呢?那就要来看进来的例子了。这个例子也是来自C++GUI Programming with Qt 4, 2nd Edition这本书的。
还是先来看代码吧:
citymodel.h
class CityModel : public QAbstractTableModel
{
Q_OBJECT
public:
CityModel(QObject *parent = 0);
void setCities(const QStringList &cityNames);
int rowCount(const QModelIndex &parent) const;
int columnCount(const QModelIndex &parent) const;
QVariant data(const QModelIndex &index, int role) const;
bool setData(const QModelIndex &index, const QVariant &value, int role);
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
Qt::ItemFlags flags(const QModelIndex &index) const;
private:
int offsetOf(int row, int column) const;
QStringList cities;
QVector<int> distances;
};
citymodel.cpp
CityModel::CityModel(QObject *parent)
: QAbstractTableModel(parent)
{
}
int CityModel::rowCount(const QModelIndex & parent) const
{
return cities.count();
}
int CityModel::columnCount(const QModelIndex & parent) const
{
return cities.count();
}
QVariant CityModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid()) {
return QVariant();
}
if (role == Qt::TextAlignmentRole) {
return int(Qt::AlignRight | Qt::AlignVCenter);
} else if (role == Qt::DisplayRole) {
if (index.row() == index.column()) {
return 0;
}
int offset = offsetOf(index.row(), index.column());
return distances[offset];
}
return QVariant();
}
QVariant CityModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role == Qt::DisplayRole) {
return cities[section];
}
return QVariant();
}
bool CityModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (index.isValid() && index.row() != index.column() && role == Qt::EditRole) {
int offset = offsetOf(index.row(), index.column());
distances[offset] = value.toInt();
QModelIndex transposedIndex = createIndex(index.column(), index.row());
emit dataChanged(index, index);
emit dataChanged(transposedIndex, transposedIndex);
return true;
}
return false;
}
Qt::ItemFlags CityModel::flags(const QModelIndex &index) const
{
Qt::ItemFlags flags = QAbstractItemModel::flags(index);
if (index.row() != index.column()) {
flags |= Qt::ItemIsEditable;
}
return flags;
}
void CityModel::setCities(const QStringList &