Qml implement my own changable contentItem property
-
Hello. I have a custom QML component (MyComponent) which has a content item it animates in various ways. I want users to be able to change this default content item using a contentItem property similar to how many other QML components work. How can this be achieved?
For example:
ApplicationWindow { MyComponent { contentItem: Rectangle { color: "yellow" } } }
In my custom component I originally had a standard Rectangle item which I converted to a property in the following way, but as soon as I turn a child item into a property I can no longer see it:
// This rectangle is invisible property Rectangle contentItem: Rectangle { id: content_item x: (root.width / 2) - (content_item.width / 2) y: 0 width: Math.min(root.width * 0.7, 400) height: Math.min(root.height * 0.7, 400) color: "blue" }
// This rectangle is visible but can't be changed in another file Rectangle { id: content_item x: (root.width / 2) - (content_item.width / 2) y: 0 width: Math.min(root.width * 0.7, 400) height: Math.min(root.height * 0.7, 400) color: "blue" }
I also tried using a property alias but got the error it was read only when I tried to reassign it in an external QML file.
Any help would be appreciated, thanks.
-
Can you post complete example ?
-
Well since i dont know how to achieve what I want it is hard to provide code. But I can provide code demonstrating what I showed above where the property item is invisible for some reason when converted to a property:
main.qml
import QtQuick 2.15 import QtQuick.Window 2.15 import QtQuick.Controls 2.0 ApplicationWindow { width: 640 height: 480 visible: true title: qsTr("Hello World") MyComponent { anchors.fill: parent } }
MyComponent.qml
import QtQuick 2.0 Rectangle { id: root color: "red" property Rectangle contentItem: Rectangle { id: content_item anchors.fill: parent color: "blue" } }
With this code (Qt 5.15.2) the application is red, but should be blue.
-
If I understand you correctly -
default
property is what you need. You can see this example for more info.