如何创建一个“类似数组”的数组JS代码可以就地修改的属性吗?
我有一个 QObject
派生类,如下所示:
class TestObject : public QObject
{
Q_OBJECT
Q_PROPERTY(QStringList contents READ contents WRITE setContents)
public:
QStringList contents() { return m_contents; }
void setContents(QStringList contents) { m_contents = contents; }
private:
QStringList m_contents;
};
该类包含一个属性,该属性是 QString
的列表。如果我想向脚本公开此类的实例,我可以使用以下命令来实现:
// Instance
TestObject test_instance;
// Expose it to the script engine
QScriptEngine script_engine;
QScriptValue val;
val = script_engine.newQObject(&test_instance);
engine.globalObject().setProperty("TestObject", val);
但是,当我在 Javascript 代码中向列表中添加字符串时,它实际上并没有添加该字符串
TestObject.contents.push("Test string!");
print(TestObject.contents.length);
:上面是0
,表示该字符串没有添加到列表中。仔细检查 MOC 生成的代码可以发现,当访问属性 contents
时,仅调用 contents()
函数,该函数返回列表的副本,该列表将被调用。项目已添加。原名单未作修改。
如何保留对列表的更改?
I have a QObject
-derived class that looks like this:
class TestObject : public QObject
{
Q_OBJECT
Q_PROPERTY(QStringList contents READ contents WRITE setContents)
public:
QStringList contents() { return m_contents; }
void setContents(QStringList contents) { m_contents = contents; }
private:
QStringList m_contents;
};
The class contains one property that is a list of QString
s. If I want to expose an instance of this class to a script, I can do so with the following:
// Instance
TestObject test_instance;
// Expose it to the script engine
QScriptEngine script_engine;
QScriptValue val;
val = script_engine.newQObject(&test_instance);
engine.globalObject().setProperty("TestObject", val);
However, when I go to add a string to the list in Javascript code, it doesn't actually add the string:
TestObject.contents.push("Test string!");
print(TestObject.contents.length);
The output of the above is 0
, indicating that the string was not added to the list. Close examination of the MOC-generated code reveals that when the property contents
is accessed, only the contents()
function is called, which returns a copy of the list to which the item is added. The original list is unmodified.
How can I have the changes to the list be persisted?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过返回对 QStringList 的引用而不是副本来解决此问题
更安全的选择是封装对内容的访问,iirc 任何声明为槽的函数都可以从 JavaScript 访问而不会出现问题,因此
也应该这样做
You can probably fix this by returning a reference to you QStringList and not a copy
The safer option is to encapsulate access to the contents, iirc any function that is declared a slot can be accessed from JavaScript without problems so
should do the trick too