Automatically select children when parent is selected in treeview
-
The index is the parent, and the children below it are well selected.
But after all the children are selected, the parent becomes unselected.Is there a way to get both parent and child selected?
void wMethodInfo::SelectModelIndex(const QModelIndex index) { //*item = m_pDirModel->itemFromIndex(index); if (this->ui.treeView->selectionMode() == QAbstractItemView::SingleSelection) return; this->ui.treeView->setSelectionMode(QAbstractItemView::MultiSelection); this->ui.treeView->selectionModel()->select(index, QItemSelectionModel::Select); for (int i = 0; i < m_pDirModel->rowCount(index); i++) { QModelIndex child = m_pDirModel->index(i, 0, index); this->ui.treeView->selectionModel()->select(child, QItemSelectionModel::Select); } }
-
@IknowQT said in Automatically select children when parent is selected in treeview:
But after all the children are selected, the parent becomes unselected.
I am "surprised" at this behaviour, but have not tested. Are you saying that as soon as you just go
this->ui.treeView->selectionModel()->select(m_pDirModel->index(0, 0, index), QItemSelectionModel::Select);
to select the first child the parent automatically becomes unselected? Maybe
QTreeView
does not allow both parent nodes and child leaves to be selected at the same time, though not sure why that would be.Additional questions I would like to delete after multiple selection.
So when Delete pressed go through all selected nodes/leaves deleting them. However note in this case it doesn't make much sense to allow children of a selected node to be selected or unselected: either way, if you are going to delete a parent node all its children will get deleted regardless.
-
Try replacing
this->ui.treeView->selectionModel()->select(index, QItemSelectionModel::Select); for (int i = 0; i < m_pDirModel->rowCount(index); i++) { QModelIndex child = m_pDirModel->index(i, 0, index); this->ui.treeView->selectionModel()->select(child, QItemSelectionModel::Select); }
with
QItemSelection selection(m_pDirModel->index(0, 0, index),m_pDirModel->index(m_pDirModel->rowCount(index)-1, 0, index)); selection.select(index,index); ui.treeView->selectionModel()->select(selection, QItemSelectionModel::Select);