I would like to emit a signal from a Qt C++ class which includes a parameter that is an array of custom objects (inherited from QObject) and receive the parameter in its qml slot, but i'm afraid it is not available at qml code. Let's say, for instance, that I have my class
class TestType : public QObject
{ Q_OBJECT Q_PROPERTY(QString name READ name) Q_PROPERTY(qint32 id READ id)
public: explicit TestType(QObject *parent = 0) : QObject(parent) {} qint32 id() const { return m_id; } void setId(qint32 id) { m_id = id; } QString name() const { return m_name; } void setName(QString name) { m_name = name; }
private: qint32 m_id; QString m_name;
};The type is registered this way:
qmlRegisterType<TestType>(uri, 0, 1, "TestType");and I have a class where i emit a signal like this
Q_SIGNALS: void mySignal(QList<TestType *> array);if I emit the signal with the array populated with several elements, if I try to read in qml slot:
onMySignal: { console.log("element:" + array[0]);
}I see "undefined" as array[0] and, obviously, any class member the array element has. When I have made tests sending a standalone TestType object as signal parameter I have got it in qml slot without any problem, but I'm not able to send an array of them.
I've tried to use QList, QmlListProperty or QVariantList with the same result. Is there any way of sending an array of custom type inherited from QObject elements as a signal parameter?
11 Answer
I've got it!This article explains how to do it perfectly
The solution is inserting TestType's in a QVariantList by using qVariantFromValue method. Then, the signal uses QVariantList as the type for all parameters that are lists
TestType *tt = new TestType(this);
QVariantList list;
list.append(qVariantFromValue((TestType*)tt));
Q_EMIT mySignal(list);the signal is declared so:
Q_SIGNALS: void mySignal(QVariantList list);Then, it can be read perfectly from qml:
onMySignal: { console.log("name of first TestType in list: " + list[0].name;
}