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 ?
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 ?
Using setCurrentIndex
should do the job:
view->setCurrentIndex(fsModel->index(0, 0));
fsModel
here can be something like view->model()
.
fsModel.sort(0)
After that index(0, 0) did actually select the first item in the view. –
Furey 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:
This is going to select and click the first item:
ui->ListWidget->setCurrentRow(0);
QListWidgetItem* item = ui->ListWidget->item(0);
ui->ListWidget->itemClicked(item);
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.
© 2022 - 2025 — McMap. All rights reserved.