Qt的script脚本除了直接使用Qt C++暴露给Qt Script的那些类以外,也可以直接new一个你自己写的Qt C++类。方法如下:
1.生成一个自己的C++类Add
- Demo.pro
QT += core script
QT -= gui
TARGET = Demo
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
SOURCES += main.cpp add.cpp
HEADERS += add.h
注意一定要加上 QT += script
- add.h
#ifndef ADD_H
#define ADD_H
#include <QObject>
class Add : public QObject
{
Q_OBJECT
public:
explicit Add(QObject *parent = 0);
public slots:
int add(int x, int y);
};
#endif // ADD_H
- add.cpp
#include "add.h"
Add::Add(QObject *parent) :
QObject(parent)
{
}
int Add::add(int x, int y)
{
return x + y;
}
2. 让Add可以在Qt script里面直接new
- 用Q_SCRIPT_DECLARE_QMETAOBJECT(Add, QObject*)来声明你的QMetaObject
- 用engine.scriptValueFromQMetaObject<Add>()来把Add变成一个QScriptValue addClass
- 把addClass暴露给QScriptEngine
#include <QtCore/QCoreApplication>
#include <QtScript>
#include <QtDebug>
#include "add.h"
Q_SCRIPT_DECLARE_QMETAOBJECT(Add, QObject*)
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QScriptEngine engine;
QScriptValue addClass = engine.scriptValueFromQMetaObject<Add>();
engine.globalObject().setProperty("Add", addClass);
engine.evaluate("f = new Add()");
qDebug()<<"3+5="<<engine.evaluate("f.add(3, 5)").toInteger();
return a.exec();
}