如何使普通的公共方法在 QtScript 中可用
在我的 Qt 应用程序中,使用 QtScript 的脚本可以访问对话框的所有控件。 为此,我使用 QScriptEngine 的 newQObject 方法,例如:
QScriptValue btn = scriptEngine->newQObject(okBtn, QScriptEngine::QtOwnership);
controls.setProperty("okButton", btn, QScriptValue::ReadOnly);
例如,我现在可以在脚本中执行此操作:
dialog.controls.okButton.setEnabled(false);
只要已发布控件 ( okButton)在对象类中被标记为公共槽。不幸的是,我希望能够从脚本调用的许多方法仅在正常的 public 范围内定义。
解决此问题的一种方法是从每个 Qt UI 元素派生一个新类,该类将这些方法重写为公共插槽。但这意味着编码和维护方面的巨大开销,在这种情况下是不可取的。
有没有办法告诉脚本引擎默认提供正常的公共函数?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据 Qt 文档,还有另一种方法可以使公共方法可被脚本访问(除了将它们声明为公共槽之外):在方法声明前面写入
Q_INVOKABLE
关键字: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:它必须是一个插槽,这是将您的函数暴露给脚本引擎的硬性要求。 Qt 对插槽做了一些额外的元对象操作,以便可以访问它们。
您是否有理由不能只创建您想要调用槽的函数?
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?