您必须在那里手动连接itemChanged
信号并选择项目。QStandardItemModel
如果您希望在选择时选中复选框,您还必须在此处连接selectionChanged
信号QListView::selectionModel()
并选中/取消选中项目。
此外,您不需要手动设置Qt::CheckStageRole
.
使用如下所示的 C++11 和 lambda:
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);
}
});
或使用旧connect
语法:
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)));