第一种方式
#include <QApplication>
#include <QMainWindow>
#include <QLabel>
#include <QVBoxLayout>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QMainWindow window;
window.setWindowTitle("超链接示例");
// 创建QLabel
QLabel *label = new QLabel("<a href=\"http://www.baidu.com\">访问百度</a>");
// 设置QLabel允许打开外部链接
label->setOpenExternalLinks(true);
// 设置窗口布局并添加QLabel
QVBoxLayout *layout = new QVBoxLayout(&window);
layout->addWidget(label);
// 显示主窗口
window.show();
return app.exec();
}
第二种方式
除了使用带有HTML标签的QLabel之外,还可以通过自定义QWidget或QLabel类并关联一个槽函数来处理点击事件,然后在槽函数中手动调用QDesktopServices的openUrl()函数来启动默认浏览器打开指定网页。这种方法不需要依赖HTML标签,更具有灵活性,但也需要更多的编码工作。
#include <QApplication>
#include <QMainWindow>
#include <QLabel>
#include <QMouseEvent>
#include <QDesktopServices>
#include <QUrl>
class CustomClickableLabel : public QLabel
{
Q_OBJECT
public:
explicit CustomClickableLabel(const QString &text, QWidget *parent = nullptr)
: QLabel(text, parent) {}
protected:
void mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
openLink("http://www.baidu.com");
}
QLabel::mousePressEvent(event);
}
private slots:
void openLink(const QString &urlStr)
{
QUrl url(urlStr);
if (QDesktopServices::openUrl(url)) {
// 成功打开链接
} else {
// 打开失败,可以在这里添加错误处理代码
}
}
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QMainWindow window;
window.setWindowTitle("自定义超链接示例");
// 创建自定义标签
CustomClickableLabel *label = new CustomClickableLabel("访问百度");
// 不需要设置任何HTML样式
QVBoxLayout *layout = new QVBoxLayout(&window);
layout->addWidget(label);
window.show();
return app.exec();
}