Разработка приложений на C++_Практическая работа №9
.pdf
Page {
objectName: "mainPage" allowedOrientations: Orientation.All
Rectangle {
id: mainRect anchors.fill: parent
property var mainRectComponent: null
Column {
id: mainColumn spacing: 5
width: parent.width property real count: 0
function deleteItems(object) { object.destroy()
}
function createItem() { var color = 'lightblue'
if (mainColumn.count % 3 === 1) color = 'lightgreen'
else if (mainColumn.count % 3 === 2) color = 'lightyellow'
mainColumn.count++
11
// Создаем компонент
var obj = itemCompont.createObject(mainColumn, {"color": color, "width": mainRect.width})
//obj.setCurentObject(obj)
obj.setCurrentText('Component' + mainColumn.count.toString()) obj.deleteThis.connect(mainColumn.deleteItems)
// Создаем компоненты в файле var obj2 =
mainRect.mainRectComponent.createObject(mainColumn, {'color': 'red'
,'width': mainRect.width}) obj2.setCurrentText('Component' +
mainColumn.count.toString() + ', From File TestComponent') obj2.deleteThis.connect(mainColumn.deleteItems)
}
}
Button {
anchors.top: mainColumn.bottom anchors.topMargin: 10 anchors.right: mainRect.right anchors.rightMargin: 10
text: 'Добавить в'
onClicked: {
12
mainColumn.createItem()
}
}
Component.onCompleted: {
if (mainRectComponent == null) mainRectComponent = mainRectComponent =
Qt.createComponent('TestCompont.qml')
}
Component {
id: itemCompont
Rectangle {
id: compontRect color: 'blue' implicitWidth: 200 implicitHeight: 50
property string currentObject: ''
signal deleteThis(var obj)
// Устанавливаем содержимое текста function setCurrentText(textName) {
interText.text = textName
}
Text {
id: interText anchors.left: parent.left
13
anchors.leftMargin: 10 anchors.verticalCenter: parent.verticalCenter text: qsTr("text")
}
Button { anchors.margins: 5 anchors.top: parent.top
anchors.bottom: parent.bottom anchors.right: parent.right text: 'Удалить'
onClicked: { compontRect.deleteThis(compontRect)
}
}
}
}
}
}
TestCompont.qml
import QtQuick 2.0 import Sailfish.Silica 1.0
Rectangle {
14
id: compontRect
color: Qt.rgba(0.8, 0.4, 0.4, 1.0) implicitWidth: 200 implicitHeight: 50
property string currentObject: ''
signal deleteThis(var obj)
// Устанавливаем содержимое текста function setCurrentText(textName) {
interText.text = textName
}
Text {
id: interText anchors.left: parent.left anchors.leftMargin: 10
anchors.verticalCenter: parent.verticalCenter text: qsTr("text")
}
Button { anchors.margins: 5 anchors.top: parent.top
anchors.bottom: parent.bottom anchors.right: parent.right text: 'Удалить'
onClicked: { compontRect.deleteThis(compontRect)
15
}
}
}
Часто мы определяем файл QML в файле, чтобы его можно было легко вызывать из других файлов QML. Вы можете напрямую использовать имя файла как имя компонента и использовать его в других файлах QML. Код в указанном выше компоненте может быть отдельно определен в файле, имя файла в этом примереTestCompont.qml
16
Источники
https://russianblogs.com/article/4279740992/
17
