PDA

View Full Version : QTreeView - how to autoselect first row?



lenardpi
24th July 2008, 21:04
Hi Everyone,

I have a QTreeView that displays some directory content using an underlying QDirModel. My problem is that when it is displayed, none of the rows is selected (ie. highlighted) in the view - I have to click on the first row for example to do that.

I want however the first row selected by default when the view shows up.

Tried some examples from the net but none worked...

Does anyone know how to achieve this?

Thanks for your help,

Istvan

jpn
24th July 2008, 21:12
#include <QtGui>

int main(int argc, char* argv[])
{
QApplication app(argc,argv);
QTreeView view;
QDirModel model;
view.setModel(&model);
view.setCurrentIndex(model.index(0, 0));
view.show();
return app.exec();
}

caduel
24th July 2008, 21:41
As a side note: I suggest to use


QAbstractItemView *view=...;
view->setCurrentIndex(view->model()->index(0, 0));

That way your code will work even when you finally decide you want to wrap your model in a QSortFilterProxyModel.

The compiler can not give you safety in the sense that a QModelIndex, a model and a view actually match (was the QModelIndex an index of the proxy or the source model again...).
Using view->model() etc makes your code improves maintainability by being more robust against such errors and model changes. And in my experience most views will sooner or later get a proxy round their model.

HTH

lenardpi
24th July 2008, 22:08
Thanks for your help!

My problem is, that when I use 3 additional lines in order to have the treeview show the entries in full row style, the autoselection does not work anymore:


#include <QtGui>

int main(int argc, char* argv[])
{
QApplication app(argc,argv);
QTreeView view;
QDirModel model;

view.setModel(&model);

// To enable full-row style:
view.setRootIndex(model.index(QDir::homePath()));
view.setItemsExpandable(false);
view.setRootIsDecorated(false);

view.setCurrentIndex(model.index(0, 0));

view.show();

return app.exec();
}

I used the whole stuff with these settings originally - I never tried without these 3 lines before, so I did not see it work...

Any idea?

Thanks

caduel
24th July 2008, 22:40
that's because model.index(0,0) is not part of the subtree shown in the view (after you have called setRootIndex).
Try


view.setCurrentIndex(model.index(0, 0, view.rootIndex()));
i.e. the first index below the root (whatever that is)

HTH

PS: this code is somewhat fragile if you happen to introduce a filter proxy later

lenardpi
24th July 2008, 22:56
Thanks a lot: that works finally!

view.setCurrentIndex(model.index(0, 0, model.index(QDir::homePath())));

works just the way I want. And thanks for the explanation, too - I haven't fully understood all the aspects of indexing in the model/view arch. yet.

Thanks all of you for the comments!

Istvan