Custom objects in QML and custom objects as properties
-
I have two classes that I have registered for use in QML.
A CreditCard class
@class CreditCard : public QObject
{
Q_OBJECTQ_ENUMS( CardType )
Q_PROPERTY( QString name READ name WRITE setName NOTIFY nameChanged )
Q_PROPERTY( QString endingIn READ endingIn WRITE setEndingIn NOTIFY endingInChanged )
Q_PROPERTY( CardType type READ type WRITE setType NOTIFY setTypeChanged )
Q_PROPERTY( QString image READ image WRITE setImage NOTIFY imageChanged )public:
explicit CreditCard(QObject *parent = 0);
CreditCard(const CreditCard &card);
CreditCard operator=(const CreditCard& card);
bool operator!=(const CreditCard& card);
bool operator==(const CreditCard& card);};@
And an Offer class
@class Offer : public QObject
{
Q_OBJECTQ_PROPERTY( QString bonus READ bonus WRITE setBonus NOTIFY bonusChanged )
Q_PROPERTY( QString condition READ condition WRITE setCondition NOTIFY conditionChanged )
Q_PROPERTY( QDateTime start READ start WRITE setStart NOTIFY startChanged )
Q_PROPERTY( QDateTime end READ end WRITE setEnd NOTIFY endChanged )
Q_PROPERTY( CreditCard card READ card WRITE setCard NOTIFY cardChanged )public:
explicit Offer(QObject *parent = 0);
Offer(const Offer& offer);
Offer operator=(const Offer& offer);
bool operator !=(const Offer& offer);
bool operator ==(const Offer& offer);};@
An Offer has a CreditCard as a property. This works fine in c++, but when I try to assign a CreditCard to an Offer in QML, like this:
@Offer{
card: CreditCard{}
}@I get an error:
@Cannot assign object to property@Even though the property DOES represent an Object. I changed the Offer class to hold a Pointer to a CreditCard and it worked... Are all custom objects actually pointers, or can I optionally assign by value?
-
Hi,
You'll need to declare the property as a pointer to a CreditCard. It is assumed that all QObjects are manipulated as pointers, for the reasons outlined in "No copy constructor or assignment operator" section of the "QObject documentation":http://doc.qt.nokia.com/4.7-snapshot/qobject.html .
Regards,
Michael -
As a small follow-up, I am passing an object from C++ to QML and it appears to be undefined. The object is a Condition object, which inherits from QObject and is registered with QML. It is returned in this function
@const Condition ConditionModel::test()
{
Condition c = new Condition();
c->setName("fish");
qDebug() << c->name();
return c;
}@From this QML code:
@ConditionModel{id:conditionModel}
MultiSelectionDialog{
id: tags
acceptButtonText: "Ok"
onAccepted: {
console.log(conditionModel.test())
}
}@The output is:
@fish
undefined@The method is marked as Q_INVOKABLE as well.. are there any other setup-gotchas that I could be missing?