在通过鼠标点击 QTextBrowser 中的链接地址时,如果是希望使用外部浏览器打开链接地址,只需要添加一行代码 ui->textBrowser->setOpenExternalLinks(true);
但如果是想知道用户点击的具体链接地址,则需要设置 ui->textBrowser->setOpenExternalLinks(false);
,另外再关联anchorClicked
信号,示例代码如下:
#include "widget.h"
#include "ui_widget.h"
#include <QDesktopServices>
#ifdef Q_OS_WIN
#include <windows.h>
#endif
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
ui->textBrowser->setOpenExternalLinks(false);
ui->textBrowser->setAlignment(Qt::AlignCenter);
ui->textBrowser->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
ui->textBrowser->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
connect(ui->textBrowser, SIGNAL(anchorClicked(const QUrl&)),this, SLOT(anchorClickedSlot(const QUrl&)));
ui->textBrowser->append("baidu.com");
ui->textBrowser->append(QString::fromLocal8Bit("<a href = \"http://www.baidu.com/\">baidu website</a>"));
ui->textBrowser->append("weixin.com");
ui->textBrowser->append(QString::fromLocal8Bit("<a href = \"https://weixin.qq.com/\">weixin website</a>"));
}
Widget::~Widget()
{
delete ui;
}
void Widget::anchorClickedSlot(const QUrl& url)
{
#ifdef Q_OS_WIN
ShellExecuteA(NULL, "open", url.toString().toStdString().c_str(), "", "", SW_SHOW);
#endif
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)