2

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?

grast
  • 21
  • 2

2 Answers2

2

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();
 };
azf
  • 2,179
  • 16
  • 22
  • This is right. But with the same reason as for Chris: I had to extend every single UI class bundled with Qt to redeclare these methods as invokable or public slots. I mean the _Window_ class in your example. Would be nice if there was a certain flag that enables availability of public methods, so I could put _QWidget_ to the script engine directly. – grast Oct 21 '11 at 11:20
  • I guess it's all related to MOC parsing source files. The Qt keywords are meant to be read by MOC, so that special features are exposed to the MetaObject engine. So does the script API you expose. No keyword, no script API – azf Dec 01 '11 at 21:02
0

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?

Chris
  • 17,119
  • 5
  • 57
  • 60
  • So you mean, there is no way for the script engine to make public methods available without this meta-object stuff. Sounds reasonable, we need names and types at runtime etc... so I have to find another way. – grast Oct 21 '11 at 11:26