一、js与c++交互
首先在所创建项目的.pro配置中添加webenginewidgets模块
QT += webenginewidgets
然后在主窗口初始化时创建QWebEngineView对象
m_webView = new QWebEngineView(this);
QStackedLayout* layout = new QStackedLayout(ui->frame);
ui->frame->setLayout(layout);
layout->addWidget(m_webView);
页面的加载和刷新
m_webView->load(url);
m_webView->reload();
辅助类JsContext
//jscontext.h
#ifndef JSCONTEXT_H
#define JSCONTEXT_H
#include <QObject>
#include <QWebEnginePage>
class JsContext : public QObject
{
Q_OBJECT
public:
explicit JsContext(QObject *parent = nullptr);
signals:
void recvdMsg(const QString& msg); //向mainwindow传递消息
public:
// 向页面发送消息
void sendMsg(QWebEnginePage* page, const QString& msg);
public slots:
// 接收到页面发送来的消息
void onMsg(const QString& msg);
};
#endif // JSCONTEXT_H
#include "jscontext.h"
JsContext::JsContext(QObject *parent) : QObject(parent)
{
}
void JsContext::onMsg(const QString &msg)
{
emit recvdMsg(msg);
}
void JsContext::sendMsg(QWebEnginePage* page, const QString& msg)
{
page->runJavaScript(QString("recvMessage('%1');").arg(msg));
}
qt端QWebChannel的使用步骤
创建QWebChannel对象;
向QWebChannel对象注册Qt对象,例子里的Qt对象就是上面实现的JsContext对象。注意:这里注册时所用的名字“context”,就是js获取qt对象时所使用的索引名。
将设置好的QWebChannel对象设置为当前页面的通道。即调用QWebEnginePage的setWebChannel方法。注意:如果没有正确注册webchannel,在js调用qt对象时会出现qt对象为undefined的情况。
#include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
m_webView = new QWebEngineView(parent);
QStackedLayout* layout = new QStackedLayout(ui->frame);
ui->frame->setLayout(layout);
layout->addWidget(m_webView);
//m_webView->load(QUrl("http://www.qt.io/"));
connect(ui->btnGo, &QPushButton::clicked, this, [this]() {
QString url = ui->addressEdit->text();
if (!url.isEmpty())
{
m_webView->load(url);
}
});
/*
connect(ui->btnRefresh, &QPushButton::clicked, this, [this]() {
m_webView->reload();
});
*/
m_jsContext = new JsContext(this);
m_webChannel = new QWebChannel(this);
m_webChannel->registerObject("context", m_jsContext);
m_webView-&