I'm working on a dialog class with a QListView
and a customized model inheriting QAbstractListModel
. Items on my list are custom widgets with several labels.
I managed to make a checkbox displayed for each item by reimplementing data()
, setData()
and flags()
methods of my model, but when I run my code and click on a checkbox associated to one of the item, the checkbox doesn't appear as checked (remains unchecked).
Here's my code:
mymodel.h
class MyModel : public QAbstractListModel
{
Q_OBJECT
public:
MyModel(QObject *parent);
int rowCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE ;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE;
bool setData(const QModelIndex & index, const QVariant & value, int role = Qt::EditRole) Q_DECL_OVERRIDE;
Qt::ItemFlags flags(const QModelIndex & index) const Q_DECL_OVERRIDE ;
QSet<QPersistentModelIndex> checkedItems;
};
mymodel.cpp
QVariant MyModel::data(const QModelIndex &index, int role) const
{
if(role == Qt::CheckStateRole)
{
if(checkedItems.contains(index))
return Qt::Checked;
else
return Qt::Unchecked;
}
return QVariant();
}
bool MyModel::setData(const QModelIndex & index, const QVariant & value, int role)
{
if(role == Qt::CheckStateRole)
{
if(value == Qt::Checked)
checkedItems.insert(index);
else
checkedItems.remove(index);
emit dataChanged(index, index);
}
return true;
}
Qt::ItemFlags MyModel::flags(const QModelIndex &index) const
{
return QAbstractListModel::flags(index) | Qt::ItemIsUserCheckable;
}
mydelegate.h
class MyDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
MyDelegate(QObject* parent = 0) : QStyledItemDelegate(parent) {}
QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const;
};
mydelegate.cpp
QSize MyDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
return QSize(400, 120);
}
In the constructor of mydialog.cpp
model = new MyModel(this);
ui->list->setModel(model);
ui->list->setItemDelegate(new MyDelegate(this));
I've tried adding flags Qt::ItemIsEnabled
and Qt::ItemIsEditable
but it didn't change anything.
I'm not very familiar with view/model implementation so far, although I've read Qt docs.
Thx for the help !