将自定义对象从 QtScript 传递到 C++ 时出错
我编写了一个自定义类,可以通过原型在 QtScript 中使用。另外还有另一个全局类可用,它应该用于打印 QtScript 中生成的自定义类。
这是我的自定义类(非常简单;)):
class Message
{
public:
int source;
int target;
};
这是我正在使用的原型:
class MessagePrototype : public QObject, public QScriptable
{
Q_OBJECT
Q_PROPERTY(int source READ getSource WRITE setSource)
Q_PROPERTY(int target READ getTarget WRITE setTarget)
public:
void setSource(const int source);
int getSource() const;
void setTarget(const int target);
int getTarget() const;
};
setter / getter 仅通过 qscriptvalue_cast(QScriptable::thisObject()); 更改/打印相应的 Message 对象;
现在我的脚本看起来像这样:
var test = new Message;
test.source = 5;
print(test.source);
GlobalObject.sendMessage(test);
所以,脚本编译正常, print() 命令执行它应该做的事情,它打印 5。但问题是我的 GlobalObject 的 sendMessage 函数:
void MessageAnalysis::sendMessage(Message msg)
{
qDebug() << "[Message]" << msg.source << msg.target;
}
这段代码总是打印:“[Message] 0 0”。
MessageAnalysis 被注册为 QtScript 的“GlobalObject”。此外,我还注册了 Message 和 Message* 作为元类型以及构造函数、原型和其他所有内容。这似乎有效。
有谁知道为什么 QtScript 中的值已更改但无法从我的 C++ 函数访问?或者我做错了什么?
I have written a custom class which is available in QtScript through a Prototype. Also another global class is available which should be used to print the custom class generated in QtScript.
This is my custom class (very simple ;) ):
class Message
{
public:
int source;
int target;
};
This is the prototype I am using:
class MessagePrototype : public QObject, public QScriptable
{
Q_OBJECT
Q_PROPERTY(int source READ getSource WRITE setSource)
Q_PROPERTY(int target READ getTarget WRITE setTarget)
public:
void setSource(const int source);
int getSource() const;
void setTarget(const int target);
int getTarget() const;
};
The setter / getter are only changing / printing the corresponding Message object through a qscriptvalue_cast(QScriptable::thisObject());
Now my script looks like this:
var test = new Message;
test.source = 5;
print(test.source);
GlobalObject.sendMessage(test);
So, the script compiles fine and the print() command does what it should, it prints 5. But the problem is the sendMessage function of my GlobalObject:
void MessageAnalysis::sendMessage(Message msg)
{
qDebug() << "[Message]" << msg.source << msg.target;
}
This piece of code always prints: "[Message] 0 0".
MessageAnalysis is registered as "GlobalObject" for QtScript. Also I have registered Message and Message* as Metatypes and the constructor, prototype and everything else. This seems to work.
Does anyone knows why the values have been changed in QtScript but are not accessible from my C++ function? Or what I am doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好的。经过几次尝试,我修复了它。
我更改了 sendMessage 函数以接受 QScriptValue 而不是 Message 作为参数。现在我可以毫无问题地从中获取属性了。
现在看来工作正常:)
Ok. After several attempts I fixed it.
I changed the sendMessage function to accept a QScriptValue instead of a Message as parameter. Now I can get the properties out of it without problems.
Seems to work fine now :)