Customizing Button with default contentItem fallback
-
wrote on 19 Aug 2024, 06:06 last edited by
Hello,
I want to customize my button so that in case I provide a contentItem, the provided one should be used. If none is provded, the default one should be used.
Something like this:
MyButton.qml import QtQuick 6.0 import QtQuick.Controls 6.0 import QtQuick.Layouts 6.0 import QtQuick.Controls.Material import QtQuick.Controls.Material.impl Item { id: root width: control.width required property var backgroundColor property var iconSize property var icon property var text property var contentItem signal clicked() Button { id: control anchors.centerIn: parent text: root.text ? root.text : undefined icon.source: root.icon ? root.icon : "" icon.height: root.iconSize ? root.iconSize : 0 icon.width: root.iconSize ? root.iconSize : 0 Material.background: root.backgroundColor ? root.backgroundColor : Material.color(Material.Grey,Material.Shade300) Material.roundedScale: Material.ExtraSmallScale contentItem: root.contentItem ? root.contentItem : control.contentItem onClicked: root.clicked() } }
Since the contentItem on a Button is not a property or an alias, I can not access it.
How do I go about this?
-
wrote on 19 Aug 2024, 10:19 last edited by
import QtQuick 6.0
import QtQuick.Controls 6.0
import QtQuick.Layouts 6.0
import QtQuick.Controls.MaterialItem {
id: root
width: control.widthrequired property var backgroundColor property var iconSize property var icon property var text property var contentItem signal clicked() Button { id: control anchors.centerIn: parent text: root.text ? root.text : undefined icon.source: root.icon ? root.icon : "" icon.height: root.iconSize ? root.iconSize : 0 icon.width: root.iconSize ? root.iconSize : 0 Material.background: root.backgroundColor ? root.backgroundColor : Material.color(Material.Grey,Material.Shade300) Material.roundedScale: Material.ExtraSmallScale contentItem: Loader { id: customContentLoader sourceComponent: root.contentItem ? root.contentItem : null onLoaded: { // Use the custom content item if provided, otherwise use the default if (!root.contentItem) { control.contentItem = control.contentItem } else { control.contentItem = customContentLoader.item } } } onClicked: root.clicked() }
}
Loader: A Loader component is used to load the custom contentItem if provided. The Loader allows for dynamically loading QML components at runtime.
sourceComponent: This property of the Loader is set to root.contentItem if it's provided. Otherwise, it remains null, meaning the loader won't load anything.
onLoaded: This handler checks if a contentItem was provided. If not, it defaults to the button's default contentItem. Otherwise, it uses the loaded contentItem.
control.contentItem: This is set to the item loaded by the Loader, or the default one.
With this setup, if you provide a custom contentItem, it will be used. If not, the button's default content will be displayed. -
1/2