Pergunta

I have this class:

class JavaScript : public QObject {    
    Q_OBJECT
    public:
        JavaScript();        
        bool executeFromFile(QString file);  
        bool enabled;

    public slots:
        void setEnabled( bool enabled );
        bool isEnabled() const;    

    private:
        QScriptEngine engine;
};

The methods are defined like this:

#include "javascript.h"

JavaScript::JavaScript() {  
    executeFromFile("test.js");
}
bool JavaScript::executeFromFile(QString file) {
    QFile scriptFile(file);
    if (!scriptFile.open(QIODevice::ReadOnly)) return false;
    QTextStream stream(&scriptFile);
    QString contents = stream.readAll();    
    scriptFile.close();
    engine.evaluate(contents, file);    
    return true;
}

void JavaScript::setEnabled( bool enabled ) {
    JavaScript::enabled = enabled;
}
bool JavaScript::isEnabled() const {
    return enabled;
}

I’m trying to access the public slots previously defined in the header file like the documentation says:

http://doc.qt.digia.com/qt/scripting.html#making-a-c-object-available-to-scripts-written-in-qtscript

The test.js file looks like this, just like the examples of the docs:

var obj = new JavaScript();
obj.setEnabled( true );
print( "obj is enabled: " + obj.isEnabled() );

But i’m not getting anything. It seems it doesn’t find the JavaScript object. What am I missing?

Doing a simple

print(1+1)

works just fine.

EDIT: An example in the qt4 webpage implements Q_PROPERTY. I tried this, but got the same result:

Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled)

EDIT 1: Tried implementing the initializer like this:

// javascript.h:

JavaScript(QObject *parent = 0);

// javascript.cpp:

JavaScript::JavaScript(QObject *parent) : QObject(parent) {}

Still nothing...

EDIT 2: Some examples inherits from QScriptable too:

class JavaScript : public QObject, public QScriptable {}

But that makes no difference either.

Foi útil?

Solução

You need to create QScriptClass instead of QObject. Qt contains example of how to extend script capabilites in Qt. Take a look on Custom Script Class Example

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top