scopchanov
scopchanov

Reputation: 8429

How to redefine an existing Q_PROPERTY as REQUIRED?

Goal

I have a QQuickItem derived C++ class, Foo, and I would like to ensure, that whoever uses it in QML, gives a value to the objectName property. In Foo I am redefining the property like this:

Q_PROPERTY(QString objectName READ objectName WRITE setObjectName NOTIFY objectNameChanged REQUIRED)

Since objectNameChanged does not take zero arguments, this alone leads to an error. So I need to also add a signal to Foo:

void objectNameChanged();

Then it compiles without errors.

Problem

The documetation states:

In QML, classes with REQUIRED properties cannot be instantiated unless all REQUIRED properties have been set.

However, when I use it like this in QML:

Foo {
    // objectName: qsTr("test) <-- commented line
}

the program compiles and runs without errors.

Question

Is there a way to change the objectName, or any other existing property for that matter, to required?

Upvotes: 1

Views: 547

Answers (1)

Inkane
Inkane

Reputation: 1500

What you could do is to expose a qml file Foo.qml which contains

CppFoo {
    required objectName
}

instead of exposing the C++ class directly to your users. Doing that for instance with a simple Item, and using it in another file would then lead to an error like

file:///tmp/tmp.aOQi2yetXl/Foo.qml:3 Required property objectName was not initialized

The fact that Q_PROPERTY(QString objectName READ objectName WRITE setObjectName NOTIFY objectNameChanged REQUIRED) did not work is probably a bug in the engine. And there's currently no feature in the C++ API to mark the property of a parent's class as required.

Upvotes: 2

Related Questions