徐高翔的个人网站

Qt-javascript扩展

2012-07-21

软硬件环境

  • ubuntu 12.10
  • Qt 4.7

前言

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

来看示例

main.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#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

1
2
3
4
5
6
7
8
9
TEMPLATE = app
TARGET =
DEPENDPATH += .
INCLUDEPATH += .

QT += webkit

HEADERS += testobject.h
SOURCES += main.cpp testobject.cpp

testobject.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#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 &param );

private slots:
void attachObject();

private:
QWebFrame *frame;
};

#endif // TESTOBJECT_H

testobject.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#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 &param )
{

//这是最终被javascript脚本调用的函数
qDebug() << "Print paramter from js script:" << param;
}

test.html

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

编译运行

1
2
3
qmake
make
./test

本文链接 https://xugaoxiang.com/2012/07/21/Qt-javascript扩展/

推荐文章(由hexo文章推荐插件驱动)

使用支付宝打赏
使用微信打赏

请博主喝咖啡!