PDA

View Full Version : Using enums in QtScript



Orphelic
20th September 2007, 08:59
Hi everybody,

I want to make a QObject scriptable using QtScript which is available in Qt 4.3. The QObject has a slot which takes an enum as an argument. My problem is that I cannot invoke this slot using QtScript. Everytime I try to do so an exception is thrown which says "unknown type 'EnumName'". You can find an example below:



// ##################
// header file Test.h
// ##################
#ifndef TEST_H
#define TEST_H

#include <QObject>
#include <QDebug>

enum MyEnum
{
FirstValue,
SecondValue
};


class Test : public QObject
{
Q_OBJECT

public:
Test(QObject *parent=0);
~Test();
public slots:
void testSlot( MyEnum arg ) { qDebug() << "Received arg" << arg; }

private:
};

#endif // TEST_H


// ##################
// Test.cpp contains empty constructor and destructor only
// ##################
#include "Test.h"

Test::Test(QObject *parent)
: QObject(parent)
{

}

Test::~Test()
{

}

// ##################
// main.cpp
// ##################

#include <QtScript>
#include <QObject>
#include <QtCore/QCoreApplication>

#include "Test.h"


int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QScriptEngine engine;

// Create Test object
Test t;
// Create ScriptValue from Test object
QScriptValue testObject = engine.newQObject(&t);
// Make testObject globally available to engine
engine.globalObject().setProperty("Test", testObject);

engine.evaluate("try { Test.testSlot(0);} catch(e) {print(e);}");

return a.exec();
}


This will produce the output "TypeError: cannot call Test::testSlot(): unknown type `MyEnum'". Changing the arguments of testSlot to ints and casting inside the slot will work but I do not like this solution very much.

My Question is: how can I make MyEnum available to the scripting engine? I tried to use Q_ENUMS, Q_DECLARE_METATYPE, Q_SCRIPT_DECLARE_QMETAOBJECT, qScriptRegisterMetaType(), etc. but I had no success so far. I guess there must be a solution but I can't find it so any help is greatly appreciated.

Thanks in advance,
Orphelic

orz
29th November 2007, 11:55
Hi Orphelic,

I had a similar problem.

I have patched MOC to generate meta-call-info for all public functions (not just slots as it is today), so I can call them from qscript, and I have set up some constructors for the classes I need to construct from qscript.

The problem arised when I tried to call the function

QDrag::exec( Qt::DropActions supportedActions = Qt::MoveAction)
from QScript.

As it turns out, the Qt::enums are not made available to the script engine. Digging a bit further, i found out that the fix was simply calling

qRegisterMetaType<Qt::DropAction>("Qt::DropAction");
first, so that Qt::DropAction was made known to the meta type system, and thus also to the script engine.

Hope this helps out,

Best regards
orz