Qt sets the QLabel hyperlink hover to appear underlined
Article directory
foreword
Because I encountered a requirement in my work, that is, when the mouse covers the hyperlink on the label, add an underline, and remove the underline when it is not covered. Therefore, there is this article to record the method to solve this problem.
QLabel set hyperlink
First of all, let's briefly introduce how to set hyperlinks in QLabel. We must know that QLabel supports HTML, so we can use HTML tags to set hyperlinks and underlines.
// 设置换行
ui->label->setWordWrap(true);
ui->label->setOpenExternalLinks(true);
ui->label->setText(u8"这是一个测试的链接<style> a {text-decoration: none} </style><a href = www.baidu.com>百度</a>,用来测试Hover");
setOpenExternalLinks
When a hyperlink is triggered, the link will be opened automatically. We cansetTextInteractionFlags
set the corresponding trigger mode by calling- In the HTML tag,
text-decoration: underline;
to set the underline of the text, <a href = > www.baidu.com> Baidu marks a hyperlink on behalf of Baidu. The content of the hyperlink is the content following the href
Back to the topic
However, in this case, only underline or no underline can be set. But we can find such an event in Qt's event category:
QEvent::CursorChange
So, here comes our inspiration. We intercept this event of QLabel, and then set the display and hiding of the underline for different mouse pointer styles. Without further ado, let's go directly to the code.
bool MainWindow::eventFilter(QObject* watched, QEvent* event)
{
if (watched == ui->label && event->type() == QEvent::CursorChange) {
auto&& cursor = ui->label->cursor();
if (cursor.shape() == Qt::PointingHandCursor) {
ui->label->setText(u8"这是一个测试的链接<style> a {text-decoration: underline;} </style><a href = www.baidu.com>百度</a>,用来测试Hover");
} else {
QTimer::singleShot(10, [this] () {
ui->label->setText(u8"这是一个测试的链接<style> a {text-decoration: none;} </style><a href = www.baidu.com>百度</a>,用来测试Hover");
});
}
}
return QWidget::eventFilter(watched, event);
}
The renderings are as follows:
Note:
Here, when changing the underline type, you cannot directly setText
enter an infinite loop. The specific reason is temporarily unknown, so you can only use a timer to trigger it temporarily.