QML che crea QML

drawing_handsL’esempio potrà sembrare banale ma, se non altro, apre la strada ad un’idea di sviluppo dell’interfaccia utente (UI) direttamente sul dispositivo. Una funzionalità in più sul “più leggero” tablet.
Prima di tutto mi serve un bottone con evento Click ed un paio di proprietà visibili come nel seguente file Button.qml .

[code lang=”CSS” smarttabs=”true” tabsize=”4″ toolbar=”true” title=”Button.qml”]
import QtQuick 2.0
Item {
id: root
width: 75
height: 25

signal clicked()
property alias label: textLabel.text
property alias color: background.color

Rectangle {
id: background
color: "lime"
anchors.fill: parent
radius: 4
}
Text {
id: textLabel
anchors.centerIn: parent
text: "Button"
}
MouseArea {
id:mousearea
anchors.fill: parent
onClicked: {
console.log("clicked!!")
parent.clicked()
}
}

}
[/code]

Il codice della pagina principale, main.qml, contiene un oggetto (Container) al quale aggiungere dei ‘figli’ creati al volo, un paio di pulsanti ed un piccolo riquadro di testo in cui inserire il codice QML da cui creare gli oggetti.

[code lang=”CSS” smarttabs=”true” tabsize=”4″ toolbar=”true” title=”main.qml”]
import QtQuick 2.0
Rectangle {
id:root
width: 800; height: 600

Item {
id: container
width: parent.width / 2
anchors {
top: root.top
left: root.left
bottom: root.bottom
}
Rectangle {
color: "lightGray"
anchors.fill: parent
}
function createObjectFromSource(source) {
var newObject = Qt.createQmlObject(source, container, "testItem1")
}
}

TextEdit {
id: code
width: parent.width / 2
anchors {
right: parent.right
top: parent.top
bottom: exitButton.top
}
text: "import QtQuick 2.0; Rectangle {color: \"red\"; width: 20; height: 20}"
focus: true
}

Button {
id:runButton
label: "Run!!"
anchors {
right: parent.right
bottom: parent.bottom
margins: 5
}
onClicked: container.createObjectFromSource(code.text)
}
Button {
id: exitButton
label: "Exit"
color: "red"
anchors {
right: runButton.left
bottom: parent.bottom
margins:5
}
onClicked: Qt.quit()
}
}
[/code]
HaveFun 🙂