news 2026/7/26 22:09:59

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/7/26 2:45:15

NVIDIA Profile Inspector完全指南:专业级显卡调校工具深度解析

NVIDIA Profile Inspector完全指南&#xff1a;专业级显卡调校工具深度解析 【免费下载链接】nvidiaProfileInspector 项目地址: https://gitcode.com/gh_mirrors/nv/nvidiaProfileInspector 想要彻底掌控NVIDIA显卡的隐藏性能&#xff1f;NVIDIA Profile Inspector正是…

作者头像 李华
网站建设 2026/7/21 21:19:17

3分钟搞定微信消息自动转发:多群同步的终极解决方案

3分钟搞定微信消息自动转发&#xff1a;多群同步的终极解决方案 【免费下载链接】wechat-forwarding 在微信群之间转发消息 项目地址: https://gitcode.com/gh_mirrors/we/wechat-forwarding 还在为手动转发微信群消息而烦恼吗&#xff1f;微信消息自动转发工具正是你需…

作者头像 李华
网站建设 2026/7/21 21:14:51

PyTorch-CUDA镜像适配A100/H100显卡实测表现

PyTorch-CUDA镜像在A100/H100上的实测表现与工程实践 在当今大模型时代&#xff0c;训练一个百亿参数级别的Transformer动辄需要数周时间——除非你手握A100或H100这样的“算力巨兽”。但现实是&#xff0c;很多团队明明配备了顶级硬件&#xff0c;却仍被环境配置、驱动冲突、…

作者头像 李华
网站建设 2026/7/21 19:21:07

浏览器个性化革命:用用户脚本重新定义你的网页体验

浏览器个性化革命&#xff1a;用用户脚本重新定义你的网页体验 【免费下载链接】greasyfork An online repository of user scripts. 项目地址: https://gitcode.com/gh_mirrors/gr/greasyfork 你是否曾对千篇一律的网页设计感到厌倦&#xff1f;是否想过让每个网站都按…

作者头像 李华
网站建设 2026/7/26 17:51:57

联想拯救者工具箱性能优化终极方案:重新定义硬件掌控的艺术

你是否曾经为笔记本性能释放不彻底而困扰&#xff1f;是否因为复杂的系统设置而错失最佳游戏体验&#xff1f;联想拯救者工具箱正是为你量身打造的硬件掌控终极方案&#xff0c;这款轻量级工具通过直接与笔记本硬件交互&#xff0c;为你提供前所未有的性能优化体验。 【免费下载…

作者头像 李华
网站建设 2026/7/21 23:07:56

Transformer模型训练提速秘籍:PyTorch+GPU环境优化指南

Transformer模型训练提速秘籍&#xff1a;PyTorchGPU环境优化指南 在深度学习项目中&#xff0c;最让人头疼的往往不是模型设计本身&#xff0c;而是“为什么我的代码跑不起来&#xff1f;”——明明复现的是顶会论文&#xff0c;结果却卡在 CUDA out of memory 或 ImportErro…

作者头像 李华