[Solved] how to detect when the selection changes in a QTreeView
I'm using a QFileSystemModel in a QTreeView and I need to detect when the selection changes. In a QTableWidget I would use the itemSelectionChanged signal but unfortunately there's no such signal for a QTreeView. I need to make sure that whatever signal I use is not only fired when a cell has been selected with the mouse but also when the keyboard is used to select a new cell. How can I accomplish this on a QTreeView?
vinb last edited by
Cant you use currentchanged()?
I notice that you compare a view with a widget. you have also a treewidget.
andre last edited by
All item views have a selection model. You might want to look into that.
I use the code below to create the file system model and tree view.
model = new QFileSystemModel(this);
tree = new QTreeView(this); tree->setModel(model); tree->setRootIndex(model->index(pathToRootFolder, 0)); tree->setAnimated(false); tree->setSortingEnabled(true); tree->sortByColumn(2, Qt::AscendingOrder); tree->setColumnWidth(0, 250); tree->setSelectionMode(QAbstractItemView::SingleSelection);
If I try to connect itemSelectionChanged or selectionChanged to the tree view it throws an error stating no such signal for the tree view.
connect(tree, SIGNAL(itemSelectionChanged()), this, SLOT(doSomethingOnNewSelection()));
"None of the available signals on a QTreeView involve detecting a selection change.":http://doc.trolltech.com/4.7/qabstractitemview.html#signals
I need to make sure that the code not only detects when an entry is clicked with the mouse but also when the user uses the arrow keys on their keyboard to navigate to a new entry.
I've tried using a QTreeWidget instead of a QTreeView but I'm presented with the error below. I'm unable to compile the code successfully if I use a QTreeWidget.
bq. error: ‘virtual void QTreeWidget::setModel(QAbstractItemModel*)’ is private
error: within this context
vinb last edited by
Why using itemselectionchanged in your connection? As you've allready started this topic with the statement that there is no such signal on the treeview.
Clearly I'm not using itemselectionchanged. I posted that comment to point out that I've already tried numerous signals on the QTreeView including the selectionChanged signal that you suggested. None of them worked. My goal was to find an alternative signal to itemSelectionChanged that was also similar in its behavior.
I was finally able to detect selection changes on the tree view by using the selection model as suggested by Andre (tree->selectionModel()) and the QItemSelectionModel's selectionChanged() signal. It seems to work as expected. Thanks for the suggestions.