Qt check for valid URL

2019-08-02 08:03发布

I am trying to create a Qt application which checks if a URL entered by the user into a text edit is valid.

This is what I have so far but it only ever says the URL entered is valid, even when I enter one which is not.

bool checkUrl(const QUrl &url) {
    if (!url.isValid()) {
        //qDebug(QString("Invalid URL: %1").arg(url.toString()));
        return false;
    }
    return true;
}

void MainWindow::on_pushButton_clicked()
{
    QString usertext = ui->plainTextEdit->toPlainText();
    QUrl url = QUrl::fromUserInput(usertext);
    if (checkUrl(url))
        ui->textEdit->setPlainText("Valid URL.");
    else
        ui->textEdit->setPlainText("Invalid URL.");
}

Also on the qDebug line there is an error:

/home/user/HTML/mainwindow.cpp:32: error: no matching function for call to ‘qDebug(QString)’

Does anyone know what the problem is as it keeps returning true?

标签: c++ qt url
2条回答
小情绪 Triste *
2楼-- · 2019-08-02 08:42

QUrl::isValid() only basically checks if the character encoding is right. What are you considering a wrong url?

Re qDebug, the form you use basically encapsulates printf, so it doesn't work with QString. You want to do:

qDebug() << QString("Invalid URL: %1").arg(url.toString());
查看更多
▲ chillily
3楼-- · 2019-08-02 08:52

You should use qDebug like this:

qDebug() << QString("Invalid URL: %1").arg(url.toString());

also note that QUrl::isValid() does not check syntax of url. You may want to use regular expressions to validate urls.

查看更多
登录 后发表回答