环境:Qt5.7.0,VS2013

一、简单介绍

从 Qt5.4 开始已经去掉 Qt WebKit 模块了,使用的是 chrome 内核封装的 QtWebEngine,浏览器相关的类有以下几个:

QWebEngineCertificateError

Information about a certificate error

QWebEngineDownloadItem

Information about a download

QWebEngineFullScreenRequest

Enables accepting or rejecting requests for entering and exiting the fullscreen mode

QWebEngineHistory

Represents the history of a web engine page

QWebEngineHistoryItem

Represents one item in the history of a web engine page

QWebEnginePage

Object to view and edit web documents

QWebEngineProfile

Web engine profile shared by multiple pages

QWebEngineScript

Encapsulates a JavaScript program

QWebEngineScriptCollection

Represents a collection of user scripts

QWebEngineSettings

Object to store the settings used by QWebEnginePage

QWebEngineView

Widget that is used to view and edit web documents

为了通过在网页和应用程序交互,需要使用另一个类 QWebChannel,它的介绍如下:

Expose QObjects to remote HTML clients.

The QWebChannel fills the gap between C++ applications and HTML/JavaScript applications. By publishing a QObject derived object to a QWebChannel and using the qwebchannel.js on the HTML side, one can transparently access properties and public slots and methods of the QObject. No manual message passing and serialization of data is required, property updates and signal emission on the C++ side get automatically transmitted to the potentially remotely running HTML clients. On the client side, a JavaScript object will be created for any published C++ QObject. It mirrors the C++ object's API and thus is intuitively useable.

The C++ QWebChannel API makes it possible to talk to any HTML client, which could run on a local or even remote machine. The only limitation is that the HTML client supports the JavaScript features used by qwebchannel.js. As such, one can interact with basically any modern HTML browser or standalone JavaScript runtime, such as node.js.

There also exists a declarative WebChannel API.

二、使用步骤

1.在 QtCreateor 中新建  Qt Widgets Application 项目,放几个控件上去,下边的是一个 widget,要用来显示网页,需要将它提升为 QWebEngineView

2.在 pro 文件中添加以下内容,注意 c++11 也是必须的

QT += webenginewidgets webchannel

CONFIG += c++11

3.从 Qt 目录下找到 qwebchannel.js 复制到项目目录,从 jquery 网站下载 jquery-3.1.1.min.js 到项目目录中

4.与网页交互的类最好从 QObject 继承(其它也可以,但可能出问题),以下是相关文件

 #ifndef WEBOBJECT_H
#define WEBOBJECT_H #include <QObject> class WebObject : public QObject
{
Q_OBJECT //供网页 JS 使用的属性
Q_PROPERTY(QString name MEMBER m_name NOTIFY sig_nameChanged)
Q_PROPERTY(int age MEMBER m_age NOTIFY sig_ageChanged) public:
explicit WebObject(QObject *parent = ); void setName(const QString& name);
void setAge(int age); signals:
void sig_nameChanged(const QString& name);
void sig_ageChanged(int age); public slots:
//供网页 JS 调用
void slot_debug(const QString& msg); private:
QString m_name;
int m_age;
}; #endif // WEBOBJECT_H

WebObject.h

 #include "WebObject.h"
#include <QDebug> WebObject::WebObject(QObject *parent) : QObject(parent)
{
m_name = "owenlang";
m_age = ;
} void WebObject::setName(const QString &name)
{
if (name != m_name)
{
m_name = name;
emit sig_nameChanged(m_name);
}
} void WebObject::setAge(int age)
{
if (age != m_age)
{
m_age = age;
emit sig_ageChanged(m_age);
}
} void WebObject::slot_debug(const QString& msg)
{
qDebug() << "web debug: " << msg;
}

WebObject.cpp

 #ifndef MAINWIDGET_H
#define MAINWIDGET_H #include <QWidget> namespace Ui {
class MainWidget;
} class WebObject;
class MainWidget : public QWidget
{
Q_OBJECT public:
explicit MainWidget(QWidget *parent = );
~MainWidget(); private slots:
void on_okBtn_clicked(); void on_callJsBtn_clicked(); private:
Ui::MainWidget *ui; WebObject * m_dataObj;
}; #endif // MAINWIDGET_H

MainWidget.h

 #include "MainWidget.h"
#include "ui_mainwidget.h"
#include "WebObject.h"
#include <QWebChannel> MainWidget::MainWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::MainWidget)
{
ui->setupUi(this);
ui->webView->load(QUrl("qrc:/index.html")); m_dataObj = new WebObject(); //重要设置
QWebChannel *channel = new QWebChannel(this);
channel->registerObject("person", m_dataObj);
ui->webView->page()->setWebChannel(channel);
} MainWidget::~MainWidget()
{
delete ui;
} void MainWidget::on_okBtn_clicked()
{
bool ok;
QString name = ui->nameEdit->text().trimmed();
int age = ui->ageEdit->text().trimmed().toInt(&ok, );
if (!ok)
{
age = ;
} m_dataObj->setName(name);
m_dataObj->setAge(age);
} void MainWidget::on_callJsBtn_clicked()
{
//执行网页 JS
QString strJs = ui->jsEdit->toPlainText();
ui->webView->page()->runJavaScript(strJs);
}

MainWidget.cpp

最后是网页 index.html,把 index.html 和 jquery,qwebchannel.js 都加入到 qrc 资料文件中

 <!doctype html>
<html>
<meta charset="utf-8">
<head>
<script src="jquery-3.1.1.min.js"></script>
<script src="qwebchannel.js"></script>
</head> <div>
<span>name:</span><input type="text" id="name"/>
<br/>
<span>age:</span><input type="text" id="age"/>
</div> <script>
'use strict'; //JS 不使用严格模式也可以 var updateName = function(text)
{
$("#name").val(text); //调用 Qt 的函数,必须是 public slots 函数
window.bridge.slot_debug("update name: " + text);
} var updateAge = function(text)
{
$("#age").val(text);
window.bridge.slot_debug("update age: " + text);
} new QWebChannel(qt.webChannelTransport, //注意 webChannelTransport 开头字母小写
function(channel){
var person = channel.objects.person;
window.bridge = person; //为了在其它位置使用
//直接使用 QObject 派生类的属性
updateName(person.name);
updateAge(person.age); //连接 Qt 的信号到 JS 函数
person.sig_nameChanged.connect(updateName);
person.sig_ageChanged.connect(updateAge);
}
); </script>
</html>

index.html

5.运行情况

6.程序打包下载:WebEngineTest.zip

7.需要注意的是,Qt5.7.0 的网页交互有一个 BUG,从另一个页面跳转到要交互的页面后,会出现 qt not defined,这个 BUG 在 Qt5.7.1 中已修复。

https://bugreports.qt.io/browse/QTBUG-54107
https://bugreports.qt.io/browse/QTBUG-53411

https://forum.qt.io/topic/68356/qt-webenginetransport-not-available-anymore
https://forum.qt.io/topic/68869/qt-is-undefined-when-i-declare-qwebchannel/2

Qt WebEngine 网页交互的更多相关文章

  1. Qt和JavaScript使用QWebChannel交互一——和Qt内嵌网页交互

    Qt和JavaScript使用QWebChannel交互一--和Qt内嵌网页交互 目录 Qt和JavaScript使用QWebChannel交互一--和Qt内嵌网页交互 前言 一.效果 二.实现过程 ...

  2. C#在WinForm中使用WebKit传递js对象实现与网页交互的方法

    这篇文章主要介绍了C#在WinForm中使用WebKit传递js对象实现与网页交互的方法,涉及针对WebBroswer控件及WebKit控件的相关使用技巧,需要的朋友可以参考下 本文实例讲述了C#在W ...

  3. Qt WebEngine版本要求

    WebEngine是Qt5.4之后加入的新特性,用Qt WebEngine取代之前的Qt Webkit http://wiki.qt.io/QtWebEngine windows版本 windows版 ...

  4. JavaScript高级用法一之事件响应与网页交互

    综述 本篇的主要内容来自慕课网,事件响应与网页交互,主要内容如下 1 什么是事件 2 鼠标单击事件( onclick ) 3 鼠标经过事件(onmouseover) 4 鼠标移开事件(onmouseo ...

  5. Communication between C++ and Javascript in Qt WebEngine(转载)

    Communication between C++ and Javascript in Qt WebEngine admin January 31, 2018 0 As Qt WebKit is re ...

  6. Qt 显示网页的控件

    Qt5.6以下的版本,基于QtWebkit控件Qt5.6以上的MSVC版本,基于 Chromium 的浏览器引擎 Qt WebEngineQt5.6以上的mingw 版本,只能采用QAxWidget ...

  7. 解决 “Project ERROR: Unknown module(s) in QT: webengine”以及“Your MaintenanceTool appears to be older than 3.0.2. .” 的办法

    1.环境 Windows10,Qt5.8.0 2.问题描述 需要使用到WebEngineView组件,在工程.pro中增加webengine后,Qt Creator应用程序输出中打印了 Project ...

  8. ios App与网页交互

    随着移动APP的快速迭代开发趋势,越来越多的APP中嵌入了html网页,但在一些大中型APP中,尤其是电商类APP,html页面已经不仅仅满足展示功能,这时html要求能与原生语言进行交互.相互传值. ...

  9. linux 下Qt WebEngine 程序打包简单记录

    本次记录仅作参考. 程序说明: 程序是一个编解码器控制管理的工具,使用到的库有:Qt的WebEngine.OpenGL模块.poco库.libmicrohttpd.libcurl.libvlc.同时程 ...

随机推荐

  1. python调win32api调整屏幕分辨率

    需要频繁切换屏幕分辨率,想写个脚本来实现,需要切换时运行一下就好 在网上查到,需要用windows的api,ChangeDisplaySettings 实现代码如下 import win32api d ...

  2. Tomcat 服务器的端口号的修改

    在系统中找到Tomcat安装目录下的conf文件夹下的servlet.xml文件. (1)在servlet.xml文件中找到以下代码: <connector port="8080&qu ...

  3. winform 读取保存配置文件

    原文连接: public static string fileName = System.IO.Path.GetFileName(Application.ExecutablePath);        ...

  4. spring3+hibernate3+(dbcp+oracle+拦截器事务配置)整合(一)

    1.applicationContext-base.xml文件 <?xml version="1.0" encoding="UTF-8"?>< ...

  5. 使用DBUtils小框架

    DBUtils对sqlserver好像支持不怎么好,经常出现问题 比如 三月 14, 2015 10:19:32 上午 com.mchange.v2.log.MLog 信息: MLog clients ...

  6. javascript获取页面文档内容

    <html> <head> <title>JavaScript基础</title> </head> <body> <p&g ...

  7. org.quartz.impl.jdbcjobstore.LockException

    说明:在使用Tomcat6.0.32+Spring3.05+Quartz1.8.6+Mysql5.5.9 此项目在我本机上没有问题,当我把mysql 脚本导入到服务器上,将数据源配置修改为服务器对应的 ...

  8. SIM卡尺寸及剪卡教程

    手机SIM卡有全尺寸SIM卡.Mini-SIM卡.Micro-SIM卡.Nano-SIM卡.Embedded-SIM卡等类型,目前主流手机基本都是趋向使用Micro-SIM卡和Nano-SM卡. 一. ...

  9. UESTC_我要长高 CDOJ 594

    韩父有N个儿子,分别是韩一,韩二…韩N.由于韩家演技功底深厚,加上他们间的密切配合,演出获得了巨大成功,票房甚至高达2000万.舟子是名很有威望的公知,可是他表面上两袖清风实则内心阴暗,看到韩家红红火 ...

  10. 关于#ifndef,#define,#end的说明

    #ifndef,#define,#end 是宏定义的一种---条件编译 这样我直接举个例子好了:我定义两个相同的类A分别在single.h和singlenew.h single.h: #include ...