Проблема в том, что rootIndex
из TreeView
не изменяется, поскольку не обновляет представление.
Одним из решений является создание свойства rootIndex
, которое возвращает индекс, помещенный в TreeView
, его необходимо изменить при создании нового пути, так как он собирается перезаписать метод setRootPath
и устранить свойство rootPathIndex
, которое было отправлено через setContextProperty()
:
main.cpp
...
class DisplayFileSystemModel : public QFileSystemModel {
Q_OBJECT
Q_PROPERTY(QModelIndex rootIndex READ rootIndex WRITE setRootIndex NOTIFY rootIndexChanged)
public:
...
Q_INVOKABLE QModelIndex setRootPath(const QString &newPath){
QModelIndex ix = QFileSystemModel::setRootPath(newPath);
setRootIndex(ix);
return ix;
}
QModelIndex rootIndex() const{
return mRootIndex;
}
void setRootIndex(const QModelIndex &rootIndex){
if(mRootIndex == rootIndex)
return;
mRootIndex = rootIndex;
Q_EMIT rootIndexChanged();
}
Q_SIGNAL void rootIndexChanged();
private:
QModelIndex mRootIndex;
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QQmlApplicationEngine engine;
qmlRegisterUncreatableType<DisplayFileSystemModel>("io.qt.examples.quick.controls.filesystembrowser", 1, 0,
"FileSystemModel", "Cannot create a FileSystemModel instance.");
DisplayFileSystemModel *fsm = new DisplayFileSystemModel(&engine); // change
fsm->setRootPath(QDir::homePath());
fsm->setResolveSymlinks(true);
engine.rootContext()->setContextProperty("fileSystemModel", fsm);
engine.load(QUrl(QStringLiteral("qrc:///main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
#include "main.moc"
main.qml
...
Row {
...
Repeater {
model: [ "rootPath", "None", "Single", "Extended", "Multi", "Contig."]
Button {
text: modelData
exclusiveGroup: eg
checkable: modelData != "rootPath"
checked: index === 1
onClicked: {
if(modelData != "rootPath")
view.selectionMode = index
else{
view.model.setRootPath("/home/myusername/test/")
}
}
}
}
}
...
TreeView {
id: view
anchors.fill: parent
anchors.margins: 2 * 12 + row.height
model: fileSystemModel
rootIndex: fileSystemModel.rootIndex //change
selection: sel
...
Полный пример можно найти по следующей ссылке .