Locate Nested Directories And Files Dynamically In Qt5/QML

Viewed 58

I have a QML application with a C++ Qt backend that is using Qt 5.12.6.

I have a txt file in the path below: "C:/Users//Documents/ParentDir/ChildDir/FinalTarget.txt"

As for several design purposes I need to reach these files under the standard DocumentsLocation.

I am trying to locate the FinalTarget.txt in a non hardcoded way in my Qml application (I don't want to hard code the absolute path of the file). I have logged the results of the locating processes as below:

console.log("RESULT1= " + StandardPaths.displayName(1));
console.log("RESULT2= " + StandardPaths.locate(1, "ParentDir", 1));

I am currently receiving the below results as logs in the Application Output:

qml: RESULT1= Documents
qml: RESULT2= file:///C:/Users/<MY_USER_NAME>/Documents/ParentDir

How can I reach the ChildDir and ultimately FinalTarget.txt since I am aiming to reach to the FinalTarget.txt in my application and do file IO processes such as reading and writing.

It would be really kind if someone could help me by showing me the right way to do this.

1 Answers

For me, the following code

Component.onCompleted: {
    console.log("RESULT1= " + StandardPaths.displayName(StandardPaths.DocumentsLocation));
    console.log("RESULT2= " + StandardPaths.locate(StandardPaths.DocumentsLocation, "ParentDir/ChildDir/FinalTarget.txt", StandardPaths.LocateFile));
}

prints

qml: RESULT1= Documents
qml: RESULT2= file:///home/mitch/Documents/ParentDir/ChildDir/FinalTarget.txt

and fails if the file doesn't exist. So it seems that the fileName argument can be a relative path.

Though I am curious why you'd want to do this from QML, since it has no API to do file IO, so you'd have to do it in C++ anyway.

Related