Qml and QfileSystemModel interaction problem
- by user136432
I'm having some problem in realizing an interaction between QML and C++ to obtain a very basic file browser that is shown within a ListView. I tried to use as model for my data the QT class QFileSystemModel, but it did't work as I expected, probably I didn't fully understand the QT class documentation about the use of this model or the example I found on the internet.
Here is the code that I am using:
File main.cpp
#include <QModelIndex>
#include <QFileSystemModel>
#include <QQmlContext>
#include <QApplication>
#include "qtquick2applicationviewer.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QFileSystemModel* model = new QFileSystemModel;
model->setRootPath("C:/");
model->setFilter(QDir::Files | QDir::AllDirs);
QtQuick2ApplicationViewer viewer;
// Make QFileSystemModel* available for QML use.
viewer.rootContext()->setContextProperty("myFileModel", model);
viewer.setMainQmlFile(QStringLiteral("qml/ProvaQML/main.qml"));
viewer.showExpanded();
return app.exec();
}
File main.qml
Rectangle
{
id: main
width: 800
height: 600
ListView
{
id: view
property string root_path: "C:/Users"
x: 40
y: 20
width: parent.width - (2*x)
height: parent.height - (2*y)
VisualDataModel
{
id: myVisualModel
model: myFileModel // Get the model QFileSystemModel exposed from C++
delegate
{
Rectangle
{
width: 210; height: 20;
radius: 5; border.width: 2; border.color: "orange"; color: "yellow";
Text { text: fileName; x: parent.x + 10; }
MouseArea
{
anchors.fill: parent
onDoubleClicked:
{
myVisualModel.rootIndex = myVisualModel.modelIndex(index)
}
}
}
}
}
highlight: Rectangle { color: "lightsteelblue"; radius: 5 }
focus: true
}
}
The first problem with this code is that first elements that I can see within my list are my PC logical drives even if I set a specific path. Then when I first double click on drive "C:\" it shows the list of files and directories on that path, but when I double click on a directory a second time the screen flickers for one moment and then it shows again the PC logical drives.
Can anyone tell me how should I use the QFileSystemModel class with a ListView QML object?
Thanks in advance!
Carlo