Qt WebEngine 网页交互

环境: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

Qt WebEngine 网页交互

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.运行情况

Qt WebEngine 网页交互

Qt WebEngine 网页交互

Qt WebEngine 网页交互

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

上一篇:从浅入深详解独立ip网站域名恶意解析的解决方案


下一篇:Html标签href的困惑记载