How to make normal public methods available in QtScript

871 Views Asked by At

In my Qt application, all controls of a dialog are accessible to scripts using QtScript. To do this I use the newQObject method of QScriptEngine, like:

QScriptValue btn = scriptEngine->newQObject(okBtn, QScriptEngine::QtOwnership);
controls.setProperty("okButton", btn, QScriptValue::ReadOnly);

E.g. I can now do this in a script:

dialog.controls.okButton.setEnabled(false);

This works fine as far as the invoked method (setEnabled) of the published control (okButton) is marked as public slot in the objects class. Unfortunately many of the methods I want to be able to call from script are only defined in normal public scope.

One way to solve this would be to derive a new class from each Qt UI element, that overrides those methods as public slots. But this implies big overhead in coding and maintenance, which is not desirable in this situation.

Is there a way to tell the script engine to make normal public functions available by default?

2

There are 2 best solutions below

1
On

It has to be a slot, this a hard requirement for your functions to be exposed to the scripting engine. Qt does some extra meta-object stuff to slots that makes it possible to access them.

Is there a reason you can't just make the functions you want to call slots as well?

2
On

There is an other way to make public methods accessible to script (beside declaring them as public slots), according to Qt doc : write the Q_INVOKABLE keyword in front of the method declaration:

 class Window : public QWidget
 {
     Q_OBJECT

 public:
     Window();
     void normalMethod();
     Q_INVOKABLE void invokableMethod();
 };