QtQuick.Controls 2.xによく使われている、propertyにItemを入れる方法。
あれを自分でも実装したかったので、調べてみました。
プロパティを用意する。
aliasでLoaderにぶち込めばうまく動きました。
MyButton.qml
Rectangle {
property alias icon : loader.sourceComponent
color: "gray"
width: 100; height: 60; radius: 5
Loader {
id: loader
anchors.centerIn: parent
}
}
上記のようにLoaderのsourceComponentにaliasを設定しておきます。
プロパティにItemを入れる。
MyButton {
x: 10
icon: Text {//ボタンの中心に「アイコン」の文字を表示
text: "アイコン"
}
}
MyButton {
x: 120
icon: Rectangle {//ボタンの中心に赤丸を表示
width: 20; height: width; radius: width/2
color: "red"
}
}
MyButton {
x: 240
icon: Image {//ボタンの中心にicon.pngを表示
source: "qrc:/icon.png"
}
}
iconにはTextだったりRectangleだったりImageだったり自作QMLだったり、なんでも配置できるようになります。
上記以外の方法。
関数でcreateObject()を使う方法とかあるみたいですけど、試してません…。