Important: Please read the Qt Code of Conduct -

set a property to a const QObject pointer C++ / QML

  • Hello,

    I'm trying to access a subclass element as a const pointer from QML (as I know I don't want to modify it from QML, just access const functions.. ). It seems to me that it should be a pretty normal workflow, but I can't find any working example and I can't get it to work.

    Here is a small example.


        qmlRegisterType<MainClass>("Test", 1, 0, "MainClass");
        qmlRegisterUncreatableType<SubClass>( "Test", 1, 0, "Subclass", QStringLiteral("SubClass should not be created in QML")


    MainClass {
        Q_PROPERTY( const SubClass* sub_element READ sub_element CONSTANT );
        const SubClass* sub_element() const { return &m_sub_element; }
       SubClass m_sub_element;


    import Test 1.0
    Rectangle {
        property MainClass element
        property SubClass sub_element : element.sub_element 

    Here everything is compiling. But when I run the code and try to call a function from sub_element I have the following error : ReferenceError: sub_element is not defined. If I remove the const everything is working fine, but I would rather not do that.

    If I remove the const from the Q_PROPERTY definition I obviously get a compilation error as I'm trying to convert a const element to a non const one.
    Changing the way I'm registering the SubClass doesn't seem to change anything (I've tried with/without const).

    I know I can go with a non const pointer but I would really like to understand why I should have such a limitation..