上篇中,我们写到了自己定义了一个按钮,但是呢,按照这样的写法,要写一个程序出来,那要累死了,所以,qml给我的感觉就是各种随便调用,所以了,可以自己写一个自己Button的qml,这样在以后用到了,就可以直接使用了。
上运行截图
在上面的关闭按钮了,就是我们上篇文章里面写到的那个自定义的按钮,下面的这个text的按钮了,就是使用我们自己定义的一个类,MyButton
import QtQuick 2.0 import QtQuick.Controls 1.4 /************************************************ Date:2017年4月3日 Author:DreanLife About:写一个自己定义的按钮 **********************************************/ Rectangle { property string nomal_Image: "" property string hover_Image: "" property string press_Image: "" // property string currentImage: "" id:root_Button 50 height: 30 color: "transparent" state: "nomal" Image { id: button_Background anchors.fill: parent fillMode: Image.PreserveAspectFit source: nomal_Image } Text { id: button_Text anchors.centerIn: parent text: qsTr("text") } MouseArea { id:button_Mousearea anchors.fill: parent hoverEnabled: true onEntered: root_Button.state="hover" onExited: root_Button.state="nomal" onPressed: { root_Button.state="press" } } states: [ State { name: "nomal" PropertyChanges { target:button_Background source: nomal_Image } }, State { name: "hover" PropertyChanges { target: button_Background source: hover_Image } }, State { name: "press" PropertyChanges { target: button_Background source: press_Image } } ] transitions: [ Transition { from: "nomal" to: "hover" PropertyAnimation { duration: 100 } }, Transition { from: "hover" to: "press" PropertyAnimation { duration: 100 } }, Transition { from: "press" to: "nomal" PropertyAnimation { duration: 100 } } ] }
这就是一个类的完整代码了,和上篇没有太多差异,这里就累赘了,下面是这个类的使用的
MyButton { id: myButton 30 height: 30 y:30 anchors.right: parent.right nomal_Image: "qrc:/Images/button/1.png" hover_Image: "qrc:/Images/button/2.png" press_Image: "qrc:/Images/button/3.png" state: "nomal" }
这个类的使用