pro文件

#-------------------------------------------------
#
# Project created by QtCreator 2019-07-08T14:24:54
#
#-------------------------------------------------

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
QT       += core gui  network webkit webkitwidgets



TARGET = untitled29
TEMPLATE = app


SOURCES += main.cpp\
        mainwindow.cpp

HEADERS  += mainwindow.h

FORMS    += mainwindow.ui

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

public slots:
    void addJSObject();

private slots:
    void on_pEventBtn_clicked();

private:
    Ui::MainWindow *ui;

public slots:
    void jsInvokQt();

};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QWebView>
#include <QWebFrame>
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->webView->load(QUrl("file:///E:/qtTest/build-untitled29-Desktop_Qt_5_2_1_MinGW_32bit-Debug/index.html"));
    ui->webView->settings()->setAttribute(QWebSettings::JavascriptEnabled,true);
    connect(ui->webView->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()),this, SLOT(addJSObject()));   //暴露底层接口给js
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::addJSObject()
{
    ui->webView->page()->mainFrame()->addToJavaScriptWindowObject("MainWindow",this);//js调用qt对象名称
}

void MainWindow::on_pEventBtn_clicked()
{
    ui->webView->page()->mainFrame()->evaluateJavaScript("qtToJsMessage()");
}

void MainWindow::jsInvokQt()
{
    QMessageBox::information(NULL,"test","this is qt message");
}

index.html

<html>
	<head>
		<script type="text/javascript">
		function qtToJsMessage()
		{
			alert("This is javaScript MessageBox!");
		}
		function callToQtFun()
		{
			MainWindow.jsInvokQt();
		}
		</script>
	</head>
	<body>
		<input type="button" onclick="callToQtFun()" value="JsToQt" />
	</body>
</html>

源码:https://download.csdn.net/download/sinat_33859977/11300961

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐