Model-view and more switch
-
Hi!
I have the next problem.
Consider this class:
@
class XTableModel : public QAbstractTableModel
{
public:
enum ColumnOrder
{
ColumnName,
ColumnWidth,
ColumnCount
};XTableModel( QObject* parent ); ~XTableModel(); 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;
};
QVariant XTableModel::data(const QModelIndex &index, int role) const
{
if ( role == Qt::DisplayRole || role == Qt::EditRole )
{
Pen* pen = pens.[ index.row() ];
switch( index.column() )
{
case ColumnName:
return pen->name;case ColumnWidth: return pen->width; } } return QVariant();
}
QVariant XTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if ( orientation == Qt::Horizontal && role == Qt::DisplayRole )
{
switch( section )
{
case ColumnName:
return tr("Name");case ColumnWidth: return tr("Width"); } } return QVariant();
}
Qt::ItemFlags XTableModel::flags(const QModelIndex &index) const
{
Qt::ItemFlags itemFlags( Qt::ItemIsEnabled );
if ( index.column == ColumnName )
return itemFlags | Qt::ItemIsEditable;return itemFlags;
}
bool XTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{Pen* pen = pens.[ index.row() ]; switch( index.column() ) { case ColumnName: pen->name = value.toString(); break; case ColumnWidth: pen->width = value.toInt(); break; default: return false; } return true;
}
@if I want to add new column Color in my table, I will have to add case in every switch in functions data, setData, headerData and probably flags. And it's very drudgery.
What are there methods to solve this problem? -
Hi maxomato,
as the model represents the data, there is no general way for doing this. If you want to store the data in an optimal way, you have to extend your model. If you want to store your data in a general way, you could do the following:
Pen has a vector of QVariant. Each entry belongs top one column. Then you can have a generic way for doing this:
@
bool XTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{Pen* pen = pens.[ index.row() ]; if ( role == Qt::DisplayRole || role == Qt::EditRole ) { if(pen->data.count() > index.column()) { pen->data[index.column()] = value; emit dataChanged(index, index); } } return true;
}
@This is much like a QStandardItemModel works, except you only stroe data for the Displka/Edit role