Reputation: 7515
I have a QDialog, created with QT Designer, that looks like so:
The list of servers on the left is a QListView with a QStringListModel. Mouse clicking an item in the list view updates the form with the information for the selected item by connecting the view’s activated(QModelIndex) signal to a slot function in the dialog.
However, pressing up or down on the keyboard also changes the selected item, but no signal is emitted, so the form isn't updated to match the selected item. How can this be fixed?
Upvotes: 20
Views: 19135
Reputation: 124
I struggled also on a similar case with Qt6. In addition to the accepted answer, I propose this, with the new syntax it becomes (example non tested):
MyView::MyView() {
QListView* view = new QListView(this);
connect(view->selectionModel(),
&QItemSelectionModel::currentChanged,
this, &MyView::handleSelectionChanged);
}
...
MyView::handleSelectionChanged(
const QItemSelection& selection,
const QItemSelection& before){
if(selection.indexes().isEmpty()) {
clearMyView();
} else {
displayModelIndexInMyView(selection.indexes().first());
}
}
Upvotes: 0
Reputation: 33
The other way is to implement QListView::currentChanged(...)
virtual function.
Upvotes: 0
Reputation: 4414
The activated(QModelIndex)
signal actually refers to something more than just the act of selecting. The concept is rather vague, but it's more like an act of explicit choosing. If you're just looking for notification that the current selection has changed, you can grab the selection model and connect to its updates.
MyView::MyView() {
QListView* view = new QListView(this);
connect(view->selectionModel(),
SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
this, SLOT(handleSelectionChanged(QItemSelection)));
}
...
MyView::handleSelectionChanged(const QItemSelection& selection){
if(selection.indexes().isEmpty()) {
clearMyView();
} else {
displayModelIndexInMyView(selection.indexes().first());
}
}
In the code above, displayModelIndexInMyView(QModelIndex)
should be replaced with your current handler slot for activated(QModelIndex)
, and clearMyView()
replaced with whatever it is that you want to do when there's nothing selected.
There's a lot of ways to do this, and honestly I'm not sure what is the canonical one, but I think this will work for you.
Upvotes: 32