cpp call js
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QWebEngineView>
#include <QWebChannel>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void paintEvent(QPaintEvent *event);
//被js调用
Q_INVOKABLE void doSomething();
private slots:
void on_pushButton_clicked();
private:
Ui::MainWindow *ui;
QWebEngineView* webview;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
webview = new QWebEngineView(ui->verticalFrame);
webview->load(QUrl("qrc:///html/test.html"));
QWebChannel* channel = new QWebChannel(this);
channel->registerObject("mainwindow", this);
webview->page()->setWebChannel(channel);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::paintEvent(QPaintEvent *event)
{
QMainWindow::paintEvent(event);
webview->resize(ui->verticalFrame->size());
}
void MainWindow::doSomething()
{
ui->label->setText("This text has been changed by javascript!");
}
void MainWindow::on_pushButton_clicked()
{
webview->page()->runJavaScript("hello();"); //调用js
}
test.html
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script type="text/javascript" src="qrc:///qtwebchannel/qwebchannel.js"></script>
<script>
var mainwindow;
function hello()
{
document.getElementById("myText").innerHTML = "Something happened!";
alert("Good day sir, how are you?");
}
window.onload = function()
{
new QWebChannel(qt.webChannelTransport, function(channel)
{
mainwindow = channel.objects.mainwindow;
});
}
function myFunction()
{
//调用c++函数
mainwindow.doSomething();
}
</script>
</head>
<body>
<p id="myText">Hello World!</p>
<button onclick="myFunction()">Do Something</button>
</body>
</html>