prakashpun
prakashpun

Reputation: 279

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

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 ?

Upvotes: 9

Views: 8504

Answers (4)

Caldwell Ryan
Caldwell Ryan

Reputation: 11

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:

Upvotes: 1

zkunov
zkunov

Reputation: 3412

Using setCurrentIndex should do the job:

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

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

Upvotes: 13

user22220703
user22220703

Reputation: 9

This is going to select and click the first item:

ui->ListWidget->setCurrentRow(0);
QListWidgetItem* item = ui->ListWidget->item(0);
ui->ListWidget->itemClicked(item);

Upvotes: 0

snoofkin
snoofkin

Reputation: 8895

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.

Upvotes: -1

Related Questions