1. 基本类型
import QtQuick 2.0
// import the types that are required
// Declare a root element using the Rectangle type,
// which is one of the basic building blocks to create an application in QML
Rectangle {
// Give it an id so that you can refer to it later
id: page
width: 500; height: 200
color: "lightgray"
// Add a Text element as the child of the Rectangle element
// to display the text, ‘Hello world!’.
Text {
id: helloText
text: "Hello world!"
// position it at 30 pixels from the top of its parent
y: 30
// the text element is horizontally centered in the page element
anchors.horizontalCenter: page.horizontalCenter
font.pointSize: 24; font.bold: true
}
}
使用 qmlscene
工具预览界面:
D:\Qt\Qt5.12.3\5.12.3\msvc2017_64\bin\qmlscene view.qml
![](https://img.haomeiwen.com/i1993829/4659e552b5b0fd11.png)
2. QML组件
组件提供了一种定义可在其他QML文件中重用的新类型的方法。
QML组件就像一个黑盒子,通过其属性,信号和函数与外界交互,通常在自己的QML文件中定义。
组件的文件名必须始终以大写字母开头。
-
Cell.qml
import QtQuick 2.0 // The root element of the component is an Item with the id, container. // An Item is the most basic visual element in QML and is often used as a container for other elements. Item { id: container // 矩形颜色的属性的别名 cellColor property alias cellColor: rectangle.color // 参数类型为color、参数名为cellColor的信号量clicked signal clicked(color cellColor) width: 40; height: 25 // The cell component is basically a colored rectangle with the id, rectangle. Rectangle { id: rectangle border.color: "white" // 填充,使矩形的大小与其父级相同。 anchors.fill: parent } // A MouseArea enables you to react to mouse events such as clicked, hover, and so on MouseArea { anchors.fill: parent onClicked: container.clicked(container.cellColor) } }
-
main.qml
导入Cell组件来创造出颜色选择器import QtQuick 2.0 Rectangle { id: page width: 500; height: 200 color: "lightgray" Text { id: helloText text: "Hello world!" y: 30 anchors.horizontalCenter: page.horizontalCenter font.pointSize: 24; font.bold: true } Grid { id: colorPicker x: 4; anchors.bottom: page.bottom; anchors.bottomMargin: 4 rows: 2; columns: 3; spacing: 3 // Create the color picker by putting 6 cells with different colors in a grid. Cell { cellColor: "red"; onClicked: helloText.color = cellColor } Cell { cellColor: "green"; onClicked: helloText.color = cellColor } Cell { cellColor: "blue"; onClicked: helloText.color = cellColor } Cell { cellColor: "yellow"; onClicked: helloText.color = cellColor } Cell { cellColor: "steelblue"; onClicked: helloText.color = cellColor } Cell { cellColor: "black"; onClicked: helloText.color = cellColor } // When the clicked signal of a cell is triggered, // set the color of the text to the cellColor passed as a parameter. // You can react to a signal of a component through a handler of the name, ‘onSignalName’. } }
-
使用
qmlscene
工具预览:D:\Qt\Qt5.12.3\5.12.3\msvc2017_64\bin\qmlscene main.qml
color picker.png
网友评论