qt呼叫js,js呼叫qt

Dsp Tian發表於2017-09-23
複製程式碼
<html>

<script language="JavaScript">

    function qtcalljs()
    {

        alert("sdfsd");
    }


    function jscallqt()
    {
        mainWindow.dosome();
    }

</script>


<body>

<button onclick="jscallqt()" style=="height:20px;width:100px"/>


</body>
</html>
複製程式碼

qt.h:

複製程式碼
#ifndef QTTT_H
#define QTTT_H

#include <QtGui/QMainWindow>
#include <QWebKitPlatformPlugin>
#include <QWebFrame>
#include <QMessageBox>
#include <QObject>
#include "ui_qttt.h"

class qttt : public QMainWindow
{
    Q_OBJECT

public:
    qttt(QWidget *parent = 0, Qt::WFlags flags = 0);
    ~qttt();

private:
    Ui::qtttClass ui;

private slots:
    void pop();
    void addMyObjectToJavascript();
public:
    Q_INVOKABLE void dosome();
};

#endif // QTTT_H
複製程式碼

qt.cpp

複製程式碼
#include "qttt.h"

qttt::qttt(QWidget *parent, Qt::WFlags flags)
    : QMainWindow(parent, flags)
{
    ui.setupUi(this);

    ui.webView->load(QUrl("test.html"));
    connect(ui.pushButton,SIGNAL(clicked()),this,SLOT(pop()));
    connect(ui.webView->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(addMyObjectToJavascript()));


}

qttt::~qttt()
{

}

void qttt::pop()
{

    ui.webView->page()->mainFrame()->evaluateJavaScript("qtcalljs();");
}

void qttt::addMyObjectToJavascript()
{
    ui.webView->page()->mainFrame()->addToJavaScriptWindowObject("mainWindow", this);
}

void qttt::dosome()
{
    QMessageBox::aboutQt(this,"sdfsa");
}
複製程式碼

 

相關文章