news 2026/4/18 12:36:13

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/18 8:51:54

Git Commit提交代码前,请确保你的PyTorch环境一致性

Git Commit提交代码前&#xff0c;请确保你的PyTorch环境一致性 在深度学习项目开发中&#xff0c;你是否经历过这样的场景&#xff1a;本地调试一切正常&#xff0c;信心满满地 git commit 并推送到 CI 流水线后&#xff0c;构建却突然失败&#xff1f;错误日志里赫然写着 Imp…

作者头像 李华
网站建设 2026/4/18 8:55:59

Git下载大模型代码后怎么跑?一文搞定PyTorch环境依赖

Git下载大模型代码后怎么跑&#xff1f;一文搞定PyTorch环境依赖 在AI项目开发中&#xff0c;你是否经历过这样的场景&#xff1a;从GitHub上克隆了一个热门的大模型项目——可能是LLaMA微调、Stable Diffusion定制&#xff0c;或是某个顶会论文的官方实现。满怀期待地进入目录…

作者头像 李华
网站建设 2026/4/18 8:52:38

“近邻+数智”:解码智慧养老的温情答案

“近邻养老”模式与“数智”技术的融合&#xff0c;是新时代破解居家养老难题、提升养老服务品质的重要路径。这种模式以邻里互助为核心&#xff0c;以数智赋能为支撑&#xff0c;将传统人文关怀与现代科技手段相结合。进而构建起覆盖广、响应快、有温度的养老服务网络&#xf…

作者头像 李华
网站建设 2026/4/18 11:52:10

男性生育保险怎么用?准爸爸的生育津贴领取指南

很多人误以为生育保险只是准妈妈的专属福利&#xff0c;其实不然。男性职工同样缴纳生育保险&#xff0c;并在家庭生育时享有切实的权益。了解并善用这些权益&#xff0c;可以为小家庭带来一份实实在在的支持。男性生育保险的核心用途之一&#xff0c;是享受 陪产假&#xff08…

作者头像 李华
网站建设 2026/4/18 8:54:37

Altium Designer全局编辑功能在原理图中的应用

Altium Designer原理图设计提效秘籍&#xff1a;深度掌握全局编辑的实战艺术在当今电子系统日益复杂的背景下&#xff0c;一块主板上集成数百个元器件早已司空见惯。面对如此庞大的设计规模&#xff0c;你还靠“点一个改一个”来调整电阻封装&#xff1f;还在手动重命名几十条数…

作者头像 李华
网站建设 2026/4/18 8:50:58

5分钟掌握Boss直聘自动化求职神器:批量投递终极解决方案

还在为求职过程中重复点击投递按钮而烦恼吗&#xff1f;Boss直聘批量投递工具正是你需要的求职助手&#xff01;这款基于浏览器扩展的自动化求职工具能够智能筛选岗位并快速完成简历智能投递&#xff0c;让求职效率提升变得轻松简单。 【免费下载链接】boss_batch_push Boss直聘…

作者头像 李华