效果图如下
实现代码
//去除焦点选中
ui.textBrowser->setFocusPolicy(Qt::NoFocus);
//禁止滚轮滚动
ui.textBrowser->verticalScrollBar()->setEnabled(false);
//去除文案选中样式
connect(ui.textBrowser, &QTextBrowser::copyAvailable, this, [=](bool yesCopy) {
if (yesCopy)
{
QTextCursor textCursor = ui.textBrowser->textCursor();
if (textCursor.hasSelection())
{
textCursor.clearSelection();
ui.textBrowser->setTextCursor(textCursor); // 去除选中
}
}
});
QString content_word = QStringLiteral("爱过的人我已不再拥有,许多故事有伤心的理由,这一次我的爱情等不到天长地久,错过的人是否可以回首,爱过的心没有任何请求,许多故事有伤心的理由,这一次我的爱情等不到天长地久,走过的路再也不能停留");
QString word = QStringLiteral("想听完整歌曲吗?点击更多");
QString url_word = "https://y.qq.com/portal/player.html";
QString texts = QStringLiteral("%1<a style='color:#5998FF;text-decoration:none;'href=\"%2\">%3</a>").arg(content_word).arg(url_word).arg(word);
ui.textBrowser->append(texts);
QTextBrowser默认支持超链接,可以通过设置如下属性可以直接跳转页面
ui.textBrowser->setOpenLinks(true);
ui.textBrowser->setOpenExternalLinks(true);
也可以直接在ui中设置
如果需要设计其他UI交互或者功能需求,可以通过anchorClicked连接到所需逻辑的槽函数,在使用前需要禁止默认超链接属性
ui.textBrowser->setOpenLinks(false);
ui.textBrowser->setOpenExternalLinks(false);
connect(ui.textBrowser, &QTextBrowser::anchorClicked, this, &MainWidget::sltOpenURL);
槽函数实现
void MainWidget::sltOpenURL(const QUrl &url)
{
QString strUrl = url.toString();
QMessageBox::StandardButton result = QMessageBox::information(NULL, QStringLiteral("提示"), QStringLiteral("前往qq音乐?"), QMessageBox::Yes | QMessageBox::No);
switch (result)
{
case QMessageBox::Yes:
qInfo() << QStringLiteral("网页链接:") << strUrl;
QDesktopServices::openUrl(url);
break;
case QMessageBox::No:
qInfo() << QStringLiteral("无操作") ;
break;
default:
break;
}
}