Search code examples
c++qtparsingqurl

QUrl parsing in QT 5


I have a QUrl as this:

https://www.example.com/index.html#token=SomeToken&user=guest

and I want to obtain the value of the token i.e. SomeToken. I know about method QUrl::queryItemValue,so this code must work:

void MainWindow::get_token(QUrl url)
{
    url = url.toString().replace("?","#");
    QString token = url.queryItemValue("token");
}

but in Qt5 i can't use this method,how can I parse url?


Solution

  • There is new QUrlQuery class in Qt5. New QUrl doesn't support this method yet, so you should use QUrlQuery for parsing (it has this and other methods). Use

    QUrlQuery query(url);
    qDebug() << query.queryItemValue("token");
    

    Note: be carefull with replace because QUrlQuery gives you correct result with

    ?token=SomeToken not a #token=SomeToken

    http://qt-project.org/doc/qt-5/qurlquery.html