c++ - Qt Filesystembrowser:如何更改根目录和更新视图
问题描述
我正在尝试扩展 qt filesystembrowser 示例(Qt-Creator -> Welcome -> Examples -> 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/
但视图没有更新。我在这里想念什么?
解决方案
问题是rootIndex
的TreeView
不会改变,因为它不会更新视图。
一种解决方案是创建一个rootIndex
属性,该属性返回放置在 中的索引,TreeView
当建立新路径时必须更改它,因为它将覆盖该setRootPath
方法并消除rootPathIndex
通过发送的属性setContextProperty()
:
主文件
...
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
...
完整的示例可以在以下链接中找到。
推荐阅读
- python - python flask从Pycharm运行应用程序时如何从终端访问CLI
- ffmpeg - ffmpeg 交叉淡入淡出 2 张 1080p 的图片
- android - 实施 Material Design 入职示例
- amazon-web-services - Redshift Spectrum 为查询扫描的数据大小
- android - 编译期间已经存在的程序类型
- c++ - 使用 MPI c++ 进行数据交换的限制
- apache-kafka - 应该使用哪个 jmx 指标来监控 kafka 连接中连接器的状态?
- objective-c - Fabric macOS 异常有时没有被捕获?
- r - 当 gap 小于 n 时有效地完成数字
- ruby-on-rails - Ruby Rails attr_encrypted 格式加密属性