开发者

How to create an 'array-like' property that JS code can modify in place?

开发者 https://www.devze.com 2023-03-28 12:07 出处:网络
I have a QObject-derived class that looks like this: class TestObject : public QObject { Q_OBJECT Q_PROPERTY(QStringList contents READ contents WRITE setContents)

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 QStrings. 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 t开发者_JS百科o which the item is added. The original list is unmodified.

How can I have the changes to the list be persisted?


You can probably fix this by returning a reference to you QStringList and not a copy

QStringList& contents() { return m_contents; }

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

public slots:
    void addContent(QString value) { m_contents << value;}

should do the trick too

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号