1

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 to which the item is added. The original list is unmodified.

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

Nathan Osman
  • 71,149
  • 71
  • 256
  • 361

1 Answers1

0

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

Harald Scheirich
  • 9,676
  • 29
  • 53
  • The first method will not work because the MOC-generated code creates a copy of whatever the `contents()` method returns regardless of whether it is a reference or not. The second method was similar to what I ended up doing - Qt allows non-slots to be invokable from a script by prepending the declaration with `Q_INVOKABLE`. – Nathan Osman Aug 14 '11 at 19:17