You have to connect itemChanged
signal of QStandardItemModel
and select items manually there.
If you want the checkbox to be checked on selection, you'll also have to connect selectionChanged
signal of QListView::selectionModel()
and check/uncheck items there.
Also, you don't need to manually set Qt::CheckStageRole
.
Using C++11 and lambdas that would look like this:
connect(poModel, &QStandardItemModel::itemChanged, [poListView, poModel](QStandardItem * item) {
const QModelIndex index = poModel->indexFromItem(item);
QItemSelectionModel *selModel = poListView->selectionModel();
selModel->select(QItemSelection(index, index), item->checkState() == Qt::Checked ? QItemSelectionModel::Select : QItemSelectionModel::Deselect);
});
connect(poListView->selectionModel(), &QItemSelectionModel::selectionChanged, [poModel](const QItemSelection &selected, const QItemSelection &deselected) {
for (const QModelIndex &index : selected.indexes()) {
poModel->itemFromIndex(index)->setCheckState(Qt::Checked);
}
for (const QModelIndex &index : deselected.indexes()) {
poModel->itemFromIndex(index)->setCheckState(Qt::Unchecked);
}
});
Or with old connect
syntax:
void MyClass::handleCheckedChanged(QStandardItem *item) {
const QModelIndex index = item->model()->indexFromItem(item);
QItemSelectionModel *selModel = poListView->selectionModel();
selModel->select(QItemSelection(index, index), item->checkState() == Qt::Checked ? QItemSelectionModel::Select : QItemSelectionModel::Deselect);
}
void MyClass::handleSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected) {
foreach (const QModelIndex &index, selected.indexes()) {
index.model()->itemFromIndex(index)->setCheckState(Qt::Checked);
}
foreach (const QModelIndex &index, deselected.indexes()) {
index.model()->itemFromIndex(index)->setCheckState(Qt::Unchecked);
}
}
...
connect(poModel, SIGNAL(itemChanged(QStandardItem *)), this, SLOT(handleCheckedChanged(QStandardItem *)));
connect(poListView->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this, SLOT(handleSelectionChanged(QItemSelection, QItemSelection)));