PDA

View Full Version : [SOLVED] How to programattically select row in QTreeView?



TOMATO_QT
30th July 2013, 00:02
I have a simple image browser app with a QTreeView backed by a QFileSystemModel instance. The user is able select a directory using a QFileDialog. I have it working but I would like to automatically select the first item in the new directory.

I've searched around and tried many bits of code without success. I am able to set the QTreeView selection through a button press (as well of course as clicking on the QTreeView).

My code is below. The console output from the qDebug statement:

idx row 0 0
first row 0 0

idx is the selected directory index, and I don't know how to tell the treeView to select the first item within the directory.

Am I doing something obviously wrong? Any help appreciated as I've been stuck on this a while.
Setup: OSX 10.7.5 - Qt 5.1 - desktop app.





void DirBrowser::loadDirectory(const QString& dirPath)
{
imageDirectoryPath = dirPath;
saveSettings();
QModelIndex idx = dirmodel->setRootPath(imageDirectoryPath);
myTreeView->setRootIndex(idx);
myTreeView->setCurrentIndex(idx);

QModelIndex first = myTreeView->currentIndex();

qDebug() << "idx" << "row" << idx.row() << idx.column();
qDebug() << "first" << "row" << first.row() << first.column();

myTreeView->selectionModel()->select(first,
QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);

}

ChrisW67
30th July 2013, 00:15
Don't you want the index of the first child of the root index not the root index itself?

TOMATO_QT
30th July 2013, 00:48
Figured it out. The problem was that I was trying to make a selection on the `QTreeView` before the the specified directory had finished being loaded. In other words, tryng to make the selection within the method where I was changing directories.

The solution is to listen for the `directoryLoaded(QString)` `SIGNAL` that `QFileSystemModel` emits.

void QFileSystemModel::directoryLoaded ( const QString & path ) [signal]
This signal is emitted when the gatherer thread has finished to load the path.
This function was introduced in Qt 4.7.



connect(dirmodel,
SIGNAL(directoryLoaded(QString)),
this,
SLOT(model_directoryLoaded(QString)));