Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QUrl toLocalFile



  • I have a QUrl that I am creating from a string path. The path contains the # character in one of the folder names. The issue I am having is that when I do a .toLocalFile it stops at the # character. If I do a .toString it returns it fine. I also noticed that .toEncoded doesn't encode the # for some reason. Any ideas?


  • Lifetime Qt Champion

    Hi,

    AFAIK, # in a url will be considered a fragment so it might be that that you are hitting. However I don't know how it's handled for a local file path



  • @krobinson

    Hi, I can not reproduce this problem under Qt5

    #include <QtCore>
    
    int main(int argc, char *argv[])
    {
        QString file("D:\\a#b\\aaa#bbbb.txt");
        QUrl url("file:///D:/a%23b/aaa%23bbbb.txt");
    
        qDebug()<<url.toLocalFile();
        qDebug()<<QUrl::fromLocalFile(file);
        return 0;
    }
    

    The output is

    "D:/a#b/aaa#bbbb.txt"
    QUrl("file:///D:/a%23b/aaa%23bbbb.txt")
    


  • It turned out I had a lot more wrong with my path handling that just this. The differences between url and local path are a little confusing. I was grabbing the local path from a QDirIterator and then tacking on "file:///". Then I would create a QUrl from this. I think the QUrl then assumes its already in url format and doesn't encode the characters or something like that.

    I was geting the initial path from a QDirIterator.

    QString filename = it.next();

    In this case the path I get is

    D:/Test#/Test/file.txt

    Then I if I run this code.

    QUrl url("file:///" + filename);
    qDebug() << url;
    qDebug() << url.toLocalFile();

    The output is
    QUrl("file:///D:/Test#/Test/file.txt")
    "D:/Test"

    I noticed the .fromLocalFile earlier, but didn't notice when I passed it in with the file:/// already on, it was adding another. When I took a second look I released that adding it on myself was not correct. I needed to use .fromLocalFile on the file name directly coming out of the QDirIterator. Once I did this it worked great.


Log in to reply