我正在尝试扩展qt filesystembrowser示例(qt -creator-> Welcome->示例 -> filesystembrowser(。我在main.qml
Button {
id: button
x: 28
y: 12
text: qsTr("rootPath")
onClicked: {
view.model.setRoot("/home/myusername/test/")
view.update()
}
}
应该更改根目录。为此,我还添加了以下功能
Q_INVOKABLE QModelIndex setRoot(QString newPath) {
qInfo() <<"root path "<< this->rootPath();
newPath.replace(0,7,"");
setRootPath(newPath);
}
击中按钮两次后,qInfo
告诉我,现在的根路径为/home/myusername/test/
,但视图未更新。我在这里缺少什么?
问题是TreeView
的rootIndex
不更改,因为它不会更新视图。
一种解决方案是创建返回TreeView
中放置的索引的rootIndex
属性,当建立新路径时,必须更改此索引,因为它将覆盖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
...
完整的示例可以在以下链接中找到。