news 2026/4/16 14:50:08

QWebEngine 实战:自定义右键菜单、文件下载、Cookie 管理与 User-Agent 设置

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
QWebEngine 实战:自定义右键菜单、文件下载、Cookie 管理与 User-Agent 设置

QWebEngine 实战:自定义右键菜单、文件下载、Cookie 管理与 User-Agent 设置

QWebEngine基于Chromium内核,功能强大,但很多能力需要手动扩展才能满足业务需求。本文将通过四个常见场景,给出可直接使用的代码示例:

  1. 自定义右键菜单(ContextMenu)

  2. 文件下载管理(Download)

  3. Cookie 读取 / 设置 / 持久化

  4. UserAgent 自定义


1. 自定义右键菜单(Context Menu)

QWebEngineView默认使用Chromium的菜单,如果我们想接管右键菜单:

  • 禁用默认菜单:setContextMenuPolicy(Qt::CustomContextMenu)

  • 捕获右键事件

  • 自己定义QAction

  • 在页面中执行 JS 或 C++ 逻辑

1.1 右键菜单 Demo

MyWebView.h

#pragma once #include <QWebEngineView> class MyWebView : public QWebEngineView { Q_OBJECT public: explicit MyWebView(QWidget *parent = nullptr); private slots: void onCustomContextMenuRequested(const QPoint &pos); };

MyWebView.cpp

#include "MyWebView.h" #include <QMenu> #include <QClipboard> #include <QApplication> MyWebView::MyWebView(QWidget *parent) : QWebEngineView(parent) { setContextMenuPolicy(Qt::CustomContextMenu); connect(this, &QWebEngineView::customContextMenuRequested, this, &MyWebView::onCustomContextMenuRequested); } void MyWebView::onCustomContextMenuRequested(const QPoint &pos) { QMenu menu; QAction *reloadAct = menu.addAction("刷新"); QAction *copyUrlAct = menu.addAction("复制当前 URL"); QAction *inspectAct = menu.addAction("打开 DevTools"); QAction *sel = menu.exec(mapToGlobal(pos)); if (!sel) return; if (sel == reloadAct) { reload(); } elseif (sel == copyUrlAct) { QApplication::clipboard()->setText(url().toString()); } elseif (sel == inspectAct) { page()->setDevToolsPage(new QWebEnginePage(page()->profile())); } }

2. 文件下载管理(Download)

QWebEngineProfile有信号:

void downloadRequested(QWebEngineDownloadItem *download)

我们可以接管文件下载流程,比如:

  • 指定保存路径

  • 显示下载进度

  • 保存完成回调

2.1 下载示例

MainWindow 构造函数中添加:

connect(profile, &QWebEngineProfile::downloadRequested, this, &MainWindow::onDownloadRequested);

2.2 下载代码示例

void MainWindow::onDownloadRequested(QWebEngineDownloadItem *item) { QString path = QFileDialog::getSaveFileName( this, "保存文件", item->path(), ""); if (path.isEmpty()) { item->cancel(); return; } item->setPath(path); item->accept(); connect(item, &QWebEngineDownloadItem::receivedBytesChanged, this, [item]() { qDebug() << "下载进度: " << item->receivedBytes() << "/" << item->totalBytes(); }); connect(item, &QWebEngineDownloadItem::finished, this, [item]() { qDebug() << "下载完成:" << item->path(); }); }

3. 管理 Cookie(读取 / 写入 / 持久化)

Qt 的 Cookie 管理核心类:

  • QWebEngineCookieStore(从 profile 获取)

  • 支持添加、删除、监听变化

3.1 获取 CookieStore

QWebEngineCookieStore *store = page()->profile()->cookieStore();

3.2 读取 Cookie 示例

store->loadAllCookies(); connect(store, &QWebEngineCookieStore::cookieAdded, this, [](const QNetworkCookie &cookie){ qDebug() << "Cookie Added:" << cookie.name() << cookie.value(); });

3.3 设置 Cookie 示例

QNetworkCookie cookie; cookie.setName("token"); cookie.setValue("123456789"); cookie.setDomain("example.com"); cookie.setPath("/"); cookie.setExpirationDate(QDateTime::currentDateTime().addDays(7)); page()->profile()->cookieStore()->setCookie(cookie);

3.4 删除 Cookie 示例

store->deleteCookie(cookie);

3.5 Cookie 持久化

Qt 默认在 profile 中持久化Cookie,确保你使用的是持久 profile

QWebEngineProfile *profile = new QWebEngineProfile("MyProfile", this); profile->setPersistentCookiesPolicy(QWebEngineProfile::AllowPersistentCookies); profile->setPersistentStoragePath("data/profile");

4. 自定义 User-Agent

QWebEngineProfile 可设置 UA:

4.1 设置 UA

page()->profile()->setHttpUserAgent( "MyBrowser/1.0 (QtWebEngine Based)" );

4.2 在加载前动态修改 UA(可按域名区分 UA)

connect(page(), &QWebEnginePage::urlChanged, this, [this](const QUrl &url){ if (url.host().contains("mobile")) { page()->profile()->setHttpUserAgent( "Mozilla/5.0 Mobile Safari/537.36" ); } else { page()->profile()->setHttpUserAgent( "Mozilla/5.0 Desktop Safari/537.36" ); } });

5. 完整 Demo(可直接运行)

下面是一个最小项目包含:

  • 自定义右键菜单

  • 下载

  • Cookie 监听

  • UA 设置

main.cpp

#include <QApplication> #include "MainWindow.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); }

MainWindow.h

#pragma once #include <QMainWindow> #include <QWebEngineView> #include <QWebEngineProfile> class MainWindow :public QMainWindow { Q_OBJECT public: MainWindow(); private slots: void onDownloadRequested(QWebEngineDownloadItem *item); private: QWebEngineView *view; QWebEngineProfile *profile; };

MainWindow.cpp

#include "MainWindow.h" #include "MyWebView.h" #include <QVBoxLayout> #include <QFileDialog> MainWindow::MainWindow() { profile = new QWebEngineProfile("MyProfile", this); profile->setPersistentStoragePath("data/"); profile->setPersistentCookiesPolicy(QWebEngineProfile::AllowPersistentCookies); profile->setHttpUserAgent("MyQtBrowser/1.0"); view = new MyWebView(); QWebEnginePage *page = new QWebEnginePage(profile, view); view->setPage(page); connect(profile, &QWebEngineProfile::downloadRequested, this, &MainWindow::onDownloadRequested); setCentralWidget(view); view->load(QUrl("https://www.qt.io")); } void MainWindow::onDownloadRequested(QWebEngineDownloadItem *item) { QString file = QFileDialog::getSaveFileName(this, "保存文件", item->path()); if (file.isEmpty()) { item->cancel(); return; } item->setPath(file); item->accept(); }

总结

本文展示了 QWebEngine 浏览器开发中最常用的四大功能:

功能

核心类

重点

自定义右键菜单

QWebEngineView

捕获 customContextMenuRequested

文件下载管理

QWebEngineDownloadItem

接受下载、显示进度

Cookie 管理

QWebEngineCookieStore

监听、设置、持久化

User-Agent 自定义

QWebEngineProfile

动态 UA / 全局 UA

这些能力在构建桌面浏览器、内嵌网页容器、H5 AppShell 中都是必需的。

往期精彩回顾

☞QWebEngine 常用 API 全面梳理

☞ QWebEngine 系列组件全关系梳理

☞ QWebEngine 安装、环境准备与版本选择策略

关注微信公众号,获取最新文章

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/15 13:16:27

HsMod炉石传说插件终极指南:55项功能全解析与安装教程

HsMod是基于BepInEx框架开发的炉石传说功能增强插件&#xff0c;为玩家提供55项实用功能&#xff0c;从游戏性能优化到个性化定制&#xff0c;全方位提升游戏体验。这款开源插件完全免费&#xff0c;不收集用户任何个人信息&#xff0c;遵循AGPL-3.0协议&#xff0c;是炉石玩家…

作者头像 李华
网站建设 2026/4/16 14:51:16

PyTorch神经网络模块注册钩子函数(GPU兼容)

PyTorch神经网络模块注册钩子函数&#xff08;GPU兼容&#xff09; 在现代深度学习开发中&#xff0c;模型调试的复杂性早已超越了简单的“打印输出”时代。当我们在训练一个包含数十层的Transformer或ResNet时&#xff0c;若发现损失不收敛、梯度爆炸&#xff0c;甚至某些层输…

作者头像 李华
网站建设 2026/4/16 13:02:50

3分钟上手Python自动化抢票工具:告别手速极限挑战

还在为心仪演唱会门票秒空而苦恼吗&#xff1f;手动刷新总是慢人一步&#xff0c;网络延迟让你与偶像失之交臂。现在&#xff0c;基于Python的自动化抢票工具DamaiHelper让普通用户也能轻松抢到心仪的门票&#xff01; 【免费下载链接】DamaiHelper 大麦网演唱会演出抢票脚本。…

作者头像 李华
网站建设 2026/4/16 16:19:49

数字频率计设计操作指南:使用FPGA实现基础功能

用FPGA打造高精度数字频率计&#xff1a;从原理到实战的完整实现你有没有遇到过这样的场景&#xff1f;手头有个信号源&#xff0c;想测一下输出频率&#xff0c;结果示波器读数不够精确&#xff0c;单片机做的频率计又卡顿、响应慢。这时候&#xff0c;一个基于FPGA的数字频率…

作者头像 李华
网站建设 2026/4/16 16:13:19

Windows右键菜单高效优化:4步彻底清理无用菜单项

Windows右键菜单高效优化&#xff1a;4步彻底清理无用菜单项 【免费下载链接】ContextMenuManager &#x1f5b1;️ 纯粹的Windows右键菜单管理程序 项目地址: https://gitcode.com/gh_mirrors/co/ContextMenuManager 还在为Windows右键菜单中那些烦人的软件残留和杂乱无…

作者头像 李华
网站建设 2026/4/16 14:32:37

联想拯救者工具箱:轻量级笔记本性能优化终极指南

联想拯救者工具箱&#xff1a;轻量级笔记本性能优化终极指南 【免费下载链接】LenovoLegionToolkit Lightweight Lenovo Vantage and Hotkeys replacement for Lenovo Legion laptops. 项目地址: https://gitcode.com/gh_mirrors/le/LenovoLegionToolkit 还在为官方软件…

作者头像 李华