The selectedFile
property of a FormDialog looks like a URI when converted to a string:
FolderDialog {
onAccepted: monitorForm.monitorPath = selectedFolder
}
Label {
text: monitorForm.monitorPath
}
I need it to be displayed as a local path:
Another question asks for a way to do this using QML. The answers to this question implement their own ways of handling differences between platforms (except the top answer, which only works correctly on Windows and removes the leading slash on Linux). I'm hoping there's a way to leverage PySide to do this automatically.
According to the documentation, you can use the toLocalFile
function to convert a URL path to a local file path, or use fromLocalFile
for the reverse operation.
print(QUrl("file:/home/user/file.txt").toLocalFile()) # "/home/user/file.txt"
Also in QML, there is no direct method to access the toLocalFile
function of a URL object. However, in Qt 6.*, we can convert our URL to a JavaScript URL type and then retrieve the pathname
.
const path = new URL(url).pathname;
Note:
UsingURL
is not a typical method for retrieving a file path, so it should be used with caution.
Additionally, since a slash is always added to the beginning of the output path, for a Windows path, you should also append .substr(1)
at the end.
const path = new URL(url).pathname.substr(platform.os == "windows" ? 1 : 0);