news 2026/3/14 22:05:02

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/3/14 0:41:23

Jupyter Notebook魔法命令加速PyTorch代码调试

Jupyter Notebook魔法命令加速PyTorch代码调试 在深度学习项目开发中&#xff0c;一个常见的场景是&#xff1a;你刚刚修改了模型结构&#xff0c;点击“运行”后发现结果不对&#xff0c;于是开始在代码中到处加 print()&#xff0c;重启内核&#xff0c;重新加载数据……几分…

作者头像 李华
网站建设 2026/3/13 2:16:11

终极英雄联盟助手:免费快速提升游戏体验的完整解决方案

终极英雄联盟助手&#xff1a;免费快速提升游戏体验的完整解决方案 【免费下载链接】LeagueAkari ✨兴趣使然的&#xff0c;功能全面的英雄联盟工具集。支持战绩查询、自动秒选等功能。基于 LCU API。 项目地址: https://gitcode.com/gh_mirrors/le/LeagueAkari 您是否在…

作者头像 李华
网站建设 2026/3/13 13:41:00

Midscene v1.0 发布 - 视觉驱动,UI 自动化体验跃迁

文章来源&#xff5c;ByteDance Web Infra 团队 Midscene 自 2024 年开源发布以来&#xff0c;已经在 Github 斩获 11k star 、Trending 榜第二名等成绩&#xff0c;并在互联网、金融、政企、汽车等大量应用场景下完成落地。 本月&#xff0c;我们正式宣布 Midscene v1.0 发布…

作者头像 李华
网站建设 2026/3/13 14:41:48

Windows用户福音:WSL2下安装PyTorch-CUDA完整流程

Windows用户福音&#xff1a;WSL2下安装PyTorch-CUDA完整流程 在深度学习日益普及的今天&#xff0c;越来越多开发者希望在自己的Windows笔记本或台式机上快速搭建一个能跑模型、支持GPU加速的AI开发环境。然而现实往往令人头疼&#xff1a;Conda环境冲突、CUDA版本不匹配、cu…

作者头像 李华
网站建设 2026/3/13 3:44:02

从零开始学CNN:基于PyTorch-GPU环境的实战入门教程

从零开始学CNN&#xff1a;基于PyTorch-GPU环境的实战入门教程 在图像识别任务日益普及的今天&#xff0c;一个能快速响应、准确分类的模型不再是实验室里的概念&#xff0c;而是智能相机、自动驾驶、医疗影像分析等场景中的刚需。然而&#xff0c;对于刚接触深度学习的新手来说…

作者头像 李华