[英]QMessageBox - url encoding/decoding
I created a QMessageBox with an html link:我创建了一个带有 html 链接的 QMessageBox:
QTMessageBox msgBox(Utility::UI::topLevelWidget());
msgBox.setText("<a href=\"http://www.example.cz/?url=www%25www\">Link</a>");
msgBox.exec();
If I left click the link a new web browser tab opens.如果我左键单击该链接,则会打开一个新的 Web 浏览器选项卡。 The problem is that the url http://www.example.cz/?url=www**%2525**www
is opened instead of http://www.example.cz/?url=www**%25**www
问题是打开了 url http://www.example.cz/?url=www**%2525**www
而不是http://www.example.cz/?url=www**%25**www
How do I prevent such behavior?我如何防止这种行为?
UPDATE: If I right click the link, choose "Copy link" and paste it into the browser, the link is ok.更新:如果我右键单击链接,选择“复制链接”并将其粘贴到浏览器中,链接就可以了。
That's because %
has the html encoding %25
.那是因为%
具有 html 编码%25
。 So %25
-> %2525
.所以%25
-> %2525
。
Why does Qt encode the links automatically?为什么 Qt 会自动对链接进行编码?
In the QMessageBox, there is a QLabel.在 QMessageBox 中,有一个 QLabel。 The label uses the Qt::TextFormat Qt::AutoText by default .标签默认使用 Qt::TextFormat Qt::AutoText 。 Therefore, it detects in your text, that it is html encoded and generates the link.因此,它会在您的文本中检测到它是 html 编码的并生成链接。
The QLabel sends the signal linkActivated(const QString& link) or uses QDesktopServices::openUrl() , depending its the boolean openExternalLinks . QLabel 发送信号linkActivated(const QString& link)或使用QDesktopServices::openUrl() ,具体取决于其布尔值openExternalLinks 。
It seems, that the QMessageBox sets openExternalLinks
to true.似乎 QMessageBox 将openExternalLinks
设置为 true。
Since the link will be used as input for a QUrl , it will be parsed.由于链接将用作QUrl 的输入,因此将对其进行解析。 That's the reason for the double encoding.这就是双重编码的原因。
It is possible, to modify the behavior of QDesktopServices::openUrl()
by using its static method void QDesktopServices::setUrlHandler
.可以通过使用其静态方法void QDesktopServices::setUrlHandler
来修改QDesktopServices::openUrl()
的行为。 I implemented and tested it for the desired behavior:我为所需的行为实现并测试了它:
MyUrlHandler urlHandler;
QDesktopServices::setUrlHandler( "http", &urlHandler, "handleUrl" );
QMessageBox msgBox;
msgBox.setText( "<a href=\"http://www.example.cz/?url=www%25www\">Link</a>" );
msgBox.show();
Using the class MyUrlHandler
:使用类MyUrlHandler
:
class MyUrlHandler : public QObject
{
Q_OBJECT
public:
MyUrlHandler(QObject* parent=0):QObject(parent){}
public slots:
void handleUrl(const QUrl &url)
{
QDesktopServices::openUrl( QUrl::fromEncoded( url.toString().toAscii() ) );
}
};
The trick is simple, I set the link address directly to the QUrl
instance as already valid url.诀窍很简单,我将链接地址直接设置为QUrl
实例作为已经有效的 url。
But unfortunately, it modifies the behavior globally.但不幸的是,它会全局修改行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.