main.cpp
test.pro testobject.h testobject.cpp test.html
- #include <qapplication.h>
- #include <qwebview.h>
- #include "testobject.h"
- int main( int argc, char **argv )
- {
- QApplication app( argc, argv );
- QWebView *view = new QWebView();
- MyClass *myclass = new MyClass( view );
- myclass->setWebView( view );
- view->setUrl( QUrl( "test.html" ) );
- view->show();
- return app.exec();
- }
test.pro
- TEMPLATE = app
- TARGET =
- DEPENDPATH += .
- INCLUDEPATH += .
- QT += webkit
- # Input
- HEADERS += testobject.h
- SOURCES += main.cpp testobject.cpp
- #ifndef TESTOBJECT_H
- #define TESTOBJECT_H
- #include <qobject.h>
- class QWebView;
- class QWebFrame;
- class MyClass : public QObject
- {
- Q_OBJECT
- public:
- MyClass( QObject *parent );
- void setWebView( QWebView *view );
- public slots:
- void print( const QString ¶m );
- private slots:
- void attachObject();
- private:
- QWebFrame *frame;
- };
- #endif // TESTOBJECT_H
- #include <qdebug.h>
- #include <qwebview.h>
- #include <qwebframe.h>
- #include "testobject.h"
- MyClass::MyClass( QObject *parent )
- : QObject( parent )
- {
- }
- void MyClass::setWebView( QWebView *view )
- {
- QWebPage *page = view->page();
- frame = page->mainFrame();
- attachObject();
- connect( frame, SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(attachObject()) ); //当网页被载入或者刷新时,将暴露给webkit的QObject和JavaScript进行连接
- }
- void MyApi::attachObject()
- {
- frame->addToJavaScriptWindowObject( QString("MyApi"), this );//前提是使能javascript,即将JavascriptEnabled属性值设置为true;
- }
- void MyClass::print( const QString ¶m )
- {
- //这是最终被javascript脚本调用的函数
- qDebug() << "Print paramter from js script:" << param;
- }
- <html>
- <body>
- Test Page for Qt Javascript Extension!
- <script>
- MyClass.print( 'Test Page for Qt Javascript Extension!' );
- </script>
- </body>
- </html>
将以上几个文件放在一个目录下,编译测试
qmake
make
./test