环境: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. PHP学习笔记二十【静态方法】

    <?php //静态变量的基本用法 //1,在类中定义变量 //2.定义方式[访问修饰符]static 变量名 //3.访问方式self::$变量名 第二种方式,类名::$变量名 //4.在类外 ...

  2. sqlite3---代码操作

    1.创建数据库 NSString * docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainM ...

  3. C#操作Excel总结

    0. 导入命名空间:  1 2 3 4 using Microsoft.Office.Core; using Microsoft.Office.Interop.Excel; using System. ...

  4. HDU 1556 Color the ball - from lanshui_Yang

    Problem Description N个气球排成一排,从左到右依次编号为1,2,3....N.每次给定2个整数a b(a <= b),lele便为骑上他的“小飞鸽"牌电动车从气球a ...

  5. 深入了解三种针对文件(JSON、XML与INI)的配置源

    深入了解三种针对文件(JSON.XML与INI)的配置源 物理文件是我们最常用到的原始配置的载体,最佳的配置文件格式主要由三种,它们分别是JSON.XML和INI,对应的配置源类型分别是JsonCon ...

  6. python----特性001

    特性001:python 中特性的一个例子: #!/usr/local/python3.5/bin/python3 class Person(object): def __init__(self,na ...

  7. UFI命令格式里SCSI指令

    有三种字长命令:6位.10位.12位,一般Windows下用12位. 在UFI 命令格式里SCSI指令用到如下: 指令代码 指令名称 说明 04h Format Unit 格式化存储单元 12h In ...

  8. C# 编写服务 Windows service

    1.编写服务教程 http://jingyan.baidu.com/article/ea24bc395e16f8da62b331e7.html 这里不多说了. 给大家一个连接,上面有详细的教程,下面说 ...

  9. WPF笔记(1.4 布局)——Hello,WPF!

    原文:WPF笔记(1.4 布局)--Hello,WPF! 这一节只是第2章的引子.布局要使用Panel控件,有四种Panel,如下:DockPanel,就是设置停靠位置布局模型.StackPanel, ...

  10. Android ListView实现圆角

    首先呢,我们还是看几个示图: 这种带有圆角的listview' 看起来很棒吧,确实是这样,其实也不能这么说,主要方形太多了,斯通见惯就不值钱了,“物以稀为贵嘛”. 就好比学java都搞androd,很 ...