Qt中的超链接

 第一种方式
#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();
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值