Qt javascript扩展

/

软硬件环境

  • ubuntu 12.10
  • Qt 4.7

前言

所谓的Qt javascript扩展指的是将QObject对象抛出给webkit和javascript,这样前端就可以通过js去调用QObject对象的方法,这里的方法是指QObject的public slots,另外QObject的属性在javascript中也是可用的,QObject无法由QtWebkit显式地删除。

来看示例

main.cpp

  1. #include <qapplication.h>
  2. #include <qwebview.h>
  3. #include "testobject.h"
  4. int main( int argc, char **argv )
  5. {
  6. QApplication app( argc, argv );
  7. QWebView *view = new QWebView();
  8. MyClass *myclass = new MyClass( view );
  9. myclass->setWebView( view );
  10. view->setUrl( QUrl( "test.html" ) );
  11. view->show();
  12. return app.exec();
  13. }

test.pro

  1. TEMPLATE = app
  2. TARGET =
  3. DEPENDPATH += .
  4. INCLUDEPATH += .
  5. QT += webkit
  6. # Input
  7. HEADERS += testobject.h
  8. SOURCES += main.cpp testobject.cpp

testobject.h

  1. #ifndef TESTOBJECT_H
  2. #define TESTOBJECT_H
  3. #include <qobject.h>
  4. class QWebView;
  5. class QWebFrame;
  6. class MyClass : public QObject
  7. {
  8. Q_OBJECT
  9. public:
  10. MyClass( QObject *parent );
  11. void setWebView( QWebView *view );
  12. public slots:
  13. void print( const QString &param );
  14. private slots:
  15. void attachObject();
  16. private:
  17. QWebFrame *frame;
  18. };
  19. #endif // TESTOBJECT_H

testobject.cpp

  1. #include <qdebug.h>
  2. #include <qwebview.h>
  3. #include <qwebframe.h>
  4. #include "testobject.h"
  5. MyClass::MyClass( QObject *parent )
  6. : QObject( parent )
  7. {
  8. }
  9. void MyClass::setWebView( QWebView *view )
  10. {
  11. QWebPage *page = view->page();
  12. frame = page->mainFrame();
  13. attachObject();
  14. connect( frame, SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(attachObject()) ); //当网页被载入或者刷新时,将暴露给webkit的QObject和JavaScript进行连接
  15. }
  16. void MyApi::attachObject()
  17. {
  18. frame->addToJavaScriptWindowObject( QString("MyApi"), this );//前提是使能javascript,即将JavascriptEnabled属性值设置为true;
  19. }
  20. void MyClass::print( const QString &param )
  21. {
  22. //这是最终被javascript脚本调用的函数
  23. qDebug() << "Print paramter from js script:" << param;
  24. }

test.html

  1. <html>
  2. <body>
  3. Test Page for Qt Javascript Extension!
  4. <!--
  5. 这里调用MyClass的槽函数print
  1. -->
  1. <script>
  1. MyClass.print( 'Test Page for Qt Javascript Extension!' );
  1. </script>
  2. </body>
  3. </html>

编译运行

  1. qmake
  2. make
  3. ./test

转载请注明作者和出处,并添加本页链接。
原文链接: http://xugaoxiang.com/post/3

给我留言