Qt Quick——QML基础(二):自定义控件

1、新建一个QML工程,修改main.qml。

  如下,修改Window中的内容。其中Button是自定义的控件

 1 import QtQuick 2.6
 2 import QtQuick.Window 2.2
 3 
 4 Window {
 5     visible: true
 6 //    width: 360
 7 //    height: 360
 8     Button {
 9         id: button
10         x: 12; y: 12
11         text: "main Start"
12         onClicked: {
13             status.text = "Button clicked!"
14         }
15     }
16 
17     Text {
18         id: status
19         x: 12; y: 76
20         width: 116; height: 26
21         text: "waiting ..."
22         horizontalAlignment: Text.AlignHCenter
23     }
24 }

2、在main.qml所在的目录中新建一个Button,qml文件

 1 //Botton.qml
 2 import QtQuick 2.0
 3 /*
 4     文件名即自定义控件名
 5     使用别名导出属性:相当于函数的变量形参
 6         不同的是导出的属性,调用控件是可以不使用(赋值)
 7 */
 8 Rectangle {
 9     id: root
10 
11     property alias text: label.text//导出自定义属性
12     signal clicked
13 
14     width: 116; height: 26
15     color: "red"
16     border.color: "slategrey"
17 
18     Text {
19         id: label
20         anchors.centerIn: parent
21         text: "Start"
22     }
23     MouseArea {
24         anchors.fill: parent
25         onClicked: {
26             root.clicked()
27         }
28     }
29 }

猜你喜欢

转载自www.cnblogs.com/wangbin-heng/p/9576362.html