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_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 )

    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_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 )

    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:

    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": .


  • 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()
    c = new Condition();
    qDebug() << c->name();
    return c;

    From this QML code:


    id: tags
    acceptButtonText: "Ok"
    onAccepted: {

    The output is:


    The method is marked as Q_INVOKABLE as well.. are there any other setup-gotchas that I could be missing?

  • I seem to have fixed it. Apparently the pointer returned cannot be const? There are so many little things to remember when working with custom objects in QML... very cumbersome without any productive error reporting...

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.