When subclassing QAbstractTableModel, you must implement rowCount(), columnCount(), and data(). Default implementations of the index() and parent() functions are provided by QAbstractTableModel. Well behaved models will also implement headerData().
上面一段话摘自qt documents,从它可以看到,如果要实现一个自定义的tablemodel,你的实现一个派生类派生至qabstractTableModel,并重新实现rowCount和columnCount,其中前者用于表示当前table的行数,后者返回table的列数。data在界面需要更新的时候调用。并且如果要实现一个更好看的model,你还可以重新实现headerData函数。
QVariant QAbstractItemModel::data ( const QModelIndex & index, int role = Qt::DisplayRole ) const
其中index表示当前需要更新的位置,index包含了行号和列号。在Qt中role有很多种,针对每一个index,view会一次调用data来询问每一个role。
Qt::DisplayRole | 0 | The key data to be rendered in the form of text. (QString) |
Qt::DecorationRole | 1 | The data to be rendered as a decoration in the form of an icon. (QColor, QIcon or QPixmap) |
Qt::EditRole | 2 | The data in a form suitable for editing in an editor. (QString) |
Qt::ToolTipRole | 3 | The data displayed in the item's tooltip. (QString) |
Qt::StatusTipRole | 4 | The data displayed in the status bar. (QString) |
Qt::WhatsThisRole | 5 | The data displayed for the item in "What's This?" mode. (QString) |
Qt::SizeHintRole | 13 | The size hint for the item that will be supplied to views. (QSize) |
Roles describing appearance and meta data (with associated types):
Constant | Value | Description |
---|---|---|
Qt::FontRole | 6 | The font used for items rendered with the default delegate. (QFont) |
Qt::TextAlignmentRole | 7 | The alignment of the text for items rendered with the default delegate. (Qt::AlignmentFlag) |
Qt::BackgroundRole | 8 | The background brush used for items rendered with the default delegate. (QBrush) |
Qt::BackgroundColorRole | 8 | This role is obsolete. Use BackgroundRole instead. |
Qt::ForegroundRole | 9 | The foreground brush (text color, typically) used for items rendered with the default delegate. (QBrush) |
Qt::TextColorRole | 9 | This role is obsolete. Use ForegroundRole instead. |
Qt::CheckStateRole | 10 | This role is used to obtain the checked state of an item. (Qt::CheckState) |
接下来就是为了要实现可编辑,必须重新实现setData和flags函数。其中在flags函数中给相应的itme增加Qt::ItemIsEditable标记。
Qt::ItemFlags QAbstractItemModel::flags ( const QModelIndex & index ) const {
Qt::ItemFlags flag = QAbstractTableModel::flags(index);
flag |= Qt::ItemIsEditable;
return flag;
}
bool TableModel::setData(const QModelIndex &index, const QVariant &v, int role) {
if (index.isValid() && role == Qt::EditRole && v.isValid()) {
/**copy v to which data that index show*/
}
return false;
}