Signal when a QListView selection changes due to keyboard activity?

x-x picture x-x · Mar 5, 2013 · Viewed 15.2k times · Source

I have a QDialog, created with QT Designer, that looks like so: Dialog

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?

Answer

cgmb picture cgmb · Mar 5, 2013

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.