PDA

View Full Version : QTreeView/QDirModel persisting current directory selection



bigduv
3rd April 2008, 21:11
Hi, I am trying to work out how to persist the current selection in a QDirModel/QTreeView using QSettings so that I can expand the tree to that directory when the app restarts.

I am using Qt 4.3.4.

QTreeView does not appear to support saveState()/restoreState() so I guess I have to write a string URL for the currentItem() in the tree to QSettings and retrieve it later. In this case how do I convert from a string URL into a QModelItem in the View/Model?

Is there a better way to use the built in mechanisms than the one I've outlined above? I already use QSettings to persist QApplication state and table header state but I can't see any built in mechanism for doing this on a tree.

Thanks
Dave

wysota
3rd April 2008, 22:04
With QDirModel it is quite simple. Store the path in the settings and then upon initializing the application simply read it and expand its parents.

bigduv
4th April 2008, 12:00
Just to close this off I found a reasonable solution.
Calling setCurrentIndex() expands to the selected node.
Calling setExpanded() expands the selected node too.


class DirectoryTree : public QTreeView
{
public:
void readSettings(QSettings& oSettings)
{
QString sLastSelection = oSettings.value("LastSelection").toString();
if (!sLastSelection.isEmpty()) {
QModelIndex index = m_oModel.index(sLastSelection);
setCurrentIndex(index);
setExpanded(index, true);
}
}

void writeSettings(QSettings& oSettings) {
oSettings.setValue("LastSelection", m_oModel.filePath(currentIndex()));
}

protected:
QDirModel& m_oModel;
};

cheers
Dave