Qt World Summit: Submit your Presentation

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


    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");
        return 0;

    The output is


  • 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


    Then I if I run this code.

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

    The output is

    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