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 }