9

I am using QFileSystemModel along with QListView, and I want the first item shown by the model to get selected by default.

How I do that every time I click an item ?

prakashpun
  • 259
  • 4
  • 19

3 Answers3

13

Using setCurrentIndex should do the job:

view->setCurrentIndex(fsModel->index(0, 0));

fsModel here can be something like view->model().

zkunov
  • 3,362
  • 1
  • 20
  • 17
  • 9
    Just to those that don't find it obvious, fsModel here can be something like view->model() – Watcom Feb 06 '13 at 14:16
  • Doing this in Python didn't do the job. Apparently the main problem was that the underlying model IS NOT SORTED, while the QListView sorts the item by alphabet. Using index(0,0) resulted in a "random" item being selected. The solution was to sort the model first: `fsModel.sort(0)` After that index(0, 0) did actually select the first item in the view. – ChristophK Aug 12 '23 at 19:56
0

This is going to select and click the first item:

ui->ListWidget->setCurrentRow(0);
QListWidgetItem* item = ui->ListWidget->item(0);
ui->ListWidget->itemClicked(item);
  • The question was specifically about QListView and QFileSystemModel, not QListWidget. Your Answer doesn't work with a model/view system. – ChristophK Aug 12 '23 at 20:00
-1

Have you tried connecting the QListView singal:

void clicked ( const QModelIndex & index )

to a slot and reading the data from the

QModelIndex::data

It will provide the index, check if its the first one, if it is, set it.

snoofkin
  • 8,725
  • 14
  • 49
  • 86