Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the path from a QML url

Tags:

FileDialog gives a QML url variable. theurl.toString() gives something like file:///c:\foo\bar.txt. How do I get c:\foo\bar.txt?

I want to do it in a cross-platform way, and ideally without relying on regex-style hacks. QUrl provides a path() method, but I don't seem to be able to access it from QML.

like image 200
Timmmm Avatar asked Jul 24 '14 07:07

Timmmm


People also ask

How do I connect QML to C++?

All QML signals are automatically available to C++, and can be connected to using QObject::connect() like any ordinary Qt C++ signal. In return, any C++ signal can be received by a QML object using signal handlers.

How do I use a QML file in Qt?

Creating and Running QML Projects For simple UI files such as this one, select File > New File or Project > Application (Qt Quick) > Qt Quick Application - Empty from within Qt Creator. Pressing the green Run button runs the application. You should see the text Hello, World! in the center of a red rectangle.

What is QML GUI?

QML (Qt Modeling Language) is a user interface markup language. It is a declarative language (similar to CSS and JSON) for designing user interface–centric applications.


1 Answers

As noted in the comments already, there seems to be no way (yet?) to get the path itself without a regex. So this is the only way to go:

Basic solution

FileDialog {     onAccepted: {         var path = myFileDialog.fileUrl.toString();         // remove prefixed "file:///"         path = path.replace(/^(file:\/{3})/,"");         // unescape html codes like '%23' for '#'         cleanPath = decodeURIComponent(path);         console.log(cleanPath)     } } 

This regex should be quite robust as it only removes the file:/// from the beginning of the string.

You will also need to unescape some HTML characters (if the file name contains e.g. the hash #, this would be returned as %23. We decode this by using the JavaScript function decodeURIComponent()).

Fully featured example

If you not only want to filter the file:/// but also qrc:// and http://, you can use this RegEx:

^(file:\/{3})|(qrc:\/{2})|(http:\/{2}) 

So the new, complete code would be:

FileDialog {     onAccepted: {         var path = myFileDialog.fileUrl.toString();         // remove prefixed "file:///"         path= path.replace(/^(file:\/{3})|(qrc:\/{2})|(http:\/{2})/,"");         // unescape html codes like '%23' for '#'         cleanPath = decodeURIComponent(path);         console.log(cleanPath)     } } 

This is a good playground for RegEx'es: http://regex101.com/r/zC1nD5/1

like image 64
mozzbozz Avatar answered Sep 20 '22 08:09

mozzbozz