PDA

View Full Version : Checkable items for the view with QAbstractTableModel



TorAn
30th March 2010, 23:28
I have Qtreeview with the model derived from QAbstractTableModel.

All the items in the first column has to be checkable.
I implemented the flags() member function in the model that returns needed flag for the first item in each row.

Qt::ItemFlags mymodel::flags ( const QModelIndex & index ) const
{
if (! index.isValid())
return Qt::ItemFlag::NoItemFlags;

if (index.column() == 0)
{
return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemFlag::ItemIsUserCheckable;
}
else
return Qt::ItemIsSelectable | Qt::ItemIsEnabled;
}


Now, Qt::ItemFlags section of the documenation states:

checkable items need to be given both a suitable set of flags and an initial state, indicating whether the item is checked or not. This is handled automatically for model/view components

My question is: how to indicate that the "item" is checkable from within the model? I don't see any method in
QAbstractTableModel or in QModelIndex to do this.
Am I supposed to do somthing for CheckStateRole in the reimplemented "data" member functionЪ

QVariant mymodel::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::CheckStateRole)
{
??
}
....
}
}

Any help will be greatly appreciated.

Lykurg
31st March 2010, 08:29
It's Qt::CheckStateRole you are looking for.

aamer4yu
31st March 2010, 10:00
??
There you can check the item flags and return value accordingly from the data method of the model,,,,cant you ?

faldzip
31st March 2010, 11:41
Model is an interface to actual data, which are stored in some underlaying data structure. So if I would like to have a list of checkable rows in my QListView then my QAbstractItemModel subclass will contain some private member like:


QList<QPair<bool, QString> > m_modelData; // pair (checked?, name)


And in data() method it will look like this:


// . . . some checks for other roles and index validity
if (role == Qt::CheckStateRole) {
return m_modelData.at(index.row()).first ? Qt::Checked : Qt::Unchecked;
}
// . . .

I think that you assumed that this check state would be stored somewhere by the model itself, but it is you, who is supposed to write the actual data structure where this check state would be stored.
And don't forget about setData() where you have to update data in your structure while it is called with Qt::CheckStateRole.

TorAn
31st March 2010, 11:48
Thank you. After I posted my question I continued working on this issue and soon realized that I was _that close_ :) to the answer. I thank everyone who replied, but your answer stands out. Would you please submit it to Nokia for inclusion in Qt documentation? This will surely puts this question to the rest - I googled similar questions from 2004, so apparently I am not the one that missed the idea.