How to select the first item in a list view by default?
Asked Answered
L

4

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 ?

Lys answered 1/4, 2011 at 10:4 Comment(0)
R
13

Using setCurrentIndex should do the job:

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

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

Roommate answered 1/4, 2011 at 22:12 Comment(2)
Just to those that don't find it obvious, fsModel here can be something like view->model()Christadelphian
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.Furey
K
1

I had the same problem (Pyside6 python) here is my workaround (should work in c++ if you change syntax). It isn't that nice, but works!

class someClass:
    def __init__(self):
        self.fileSystemModel = QFileSystemModel()
        self.fileSystemModel.setRootPath(path)
        self.view = QListView()
        self.view.setModel(self.fileSystemModel)
        self.view.setRootIndex(self.fileSystemModel.index(self.fileSystemModel.rootPath()))
        self.fileSystemModel.layoutChanged.connect(self.updateSelectedItem)

    def updateSelectedItem(self):
        self.view.setCurrentIndex(self.view.moveCursor( QAbstractItemView.CursorAction.MoveHome,Qt.NoModifier))

The lines you are looking for are probably this two:

self.fileSystemModel.layoutChanged.connect(self.updateSelectedItem)

The directoryLoaded Signal might work as well, if you only need it on the start.

self.view.setCurrentIndex(self.view.moveCursor( QAbstractItemView.CursorAction.MoveHome,Qt.NoModifier))

moveCursor provides a QModelIndex (in this case the left-upper-corner -> MoveHome). If you use other QAbstractItemView.CursorAction like QAbstractItemView.CursorAction.MoveDown, you can select the next item.
More here:

Khoisan answered 1/8, 2024 at 17:12 Comment(0)
D
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);
Darreldarrell answered 13/7, 2023 at 9:20 Comment(1)
The question was specifically about QListView and QFileSystemModel, not QListWidget. Your Answer doesn't work with a model/view system.Furey
H
-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.

Heptode answered 1/4, 2011 at 11:3 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.