Underline appears when Qt QLabel sets hyperlink hover

Qt sets the QLabel hyperlink hover to appear underlined

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

Please add a picture description

  1. setOpenExternalLinksWhen a hyperlink is triggered, the link will be opened automatically. We can setTextInteractionFlagsset the corresponding trigger mode by calling
  2. 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:
insert image description here

Note:

Here, when changing the underline type, you cannot directly setTextenter an infinite loop. The specific reason is temporarily unknown, so you can only use a timer to trigger it temporarily.

Guess you like

Origin blog.csdn.net/qq_44723937/article/details/129911212