近来用qml写界面,经常要用到特定样式的Button,而且要用很多次,因此总会重复.本人因为不知道怎么改变系统自定义的Button的图标大小及其它属性,所以干脆用Rectangle来实现Button的功能,但缺点就是代码太多,而且重复,将其作为一个自定义组件放在单独的Qml文件中直接调用就方便且简单很多了,还不容易出错.
新建一个Qml文件,文件名首字母大写,即是调用时的控件名称,如我用的CustomButton.qml,文件内容如下:
import QtQuick 2.2
Rectangle {
id: bkgnd;
implicitWidth: 120;
implicitHeight: 50;
color: "transparent";
property alias iconSource: icon.source;
property alias iconWidth: icon.width;
property alias iconHeight: icon.height;
property alias textColor: btnText.color;
property alias font: btnText.font;
property alias text: btnText.text;
//radius: 6;
//property bool hovered: false;
// border.color: "#949494";
// border.width: hovered ? 2 : 0;
signal clicked;
Image {
id: icon;
width:parent.width
height: parent.height
source: "./images/touch.png"
fillMode: Image.PreserveAspectCrop //deng bi suo fang
clip:true //limits area
}
Text {
id: btnText;
anchors.top: icon.bottom
anchors.horizontalCenter: icon.horizontalCenter
}
MouseArea {
id: ma;
anchors.fill: parent
onPressed: {
bkgnd.scale=0.8
}
onClicked: {
//console.log("aaa")
bkgnd.scale=1
bkgnd.clicked()
}
}
}
根据需要改变其中的属性即可.
调用格式如下:
CustomButton{
id:btn3
color:"blue"
width:main.width*0.1
height:main.height*0.16
iconSource: "./images/touch.png"
text:qsTr("TouchTest")
}
需要在要调用的qml文件头部写上一句 import "路径名"
比如我的CustomButton.qml放在main.qml文件同目录的controls文件夹下,导入语句为:import "./controls".
这样就大功告成了,自定义组件中还可以添加一些其他的属性,比如动画,可以拓展试试.