qt调用js,js调用qt
<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"); }