1. 在style属性中设置其 ButtonStyle对象的background属性,用矩形作为其背景
import QtQuick 2.5
import QtQuick.Window 2.2
import QtQuick.Controls 1.4
import QtQuick.Controls.Styles 1.4
Window {
id: window
width: 500
height: 500
visible: true
Button{
id: button1
text: "Quit"
anchors.centerIn: parent
onClicked:{ //click信号
console.log("button is pressed!")
}
style: ButtonStyle {
background: Rectangle {
implicitWidth: 75
implicitHeight: 25
border.width: control.activeFocus ? 2 : 1
border.color: "green"
radius: 4
color: control.pressed ? "lightgrey" : "#eee"
}
}
}
}
2. 通过Component组件来定义一个button样式,然后通过设置style属性值为其 id 来引用
Window {
id: window
width: 500
height: 500
visible: true
Component{ //定义button 样式组件
id: btnStyle
ButtonStyle {
background: Rectangle {
implicitWidth: 75
implicitHeight: 25
border.width: control.activeFocus ? 2 : 1
border.color: (control.hovered || control.pressed)
? "green" : "#888888";
radius: 4
color: control.pressed ? "lightgrey" : "#eee"
}
}
}
Button {
id: btn1
style: btnStyle
}
Button {
id: btn2
anchors.left: btn1.right
anchors.leftMargin: 4
style: btnStyle
}
}
3.新建一个buttonStyle.qml 样式文件,然后在其它文件通过文件名buttonStyle{} 来引用。
import QtQuick 2.0
Item {
id: button
property string backColor //自定义三个属性
property string borderColor
property int borderWidth
Rectangle{ //按键背景
id: blueRec
color: button.backColor
opacity: 0.5
width: 165
height: 50
border.color: button.borderColor
border.width: button.borderWidth
radius: 20
}
MouseArea{ //按键事件
anchors.fill: blueRec
hoverEnabled: true
onEntered: {
// blueRec.color = "brown"
blueRec.rotation = 45
blueRec.border.color = "green"
name.rotation = 45
}
onExited: {
blueRec.rotation = 0
blueRec.border.color = "black"
name.rotation = 0
}
onClicked: {
Qt.quit()
}
}
Text { //按键文本
id: name
text: qsTr("Hello <b> text </b>")
anchors.centerIn: blueRec
font.pixelSize: Math.round(blueRec.height/3)
width: blueRec.width
wrapMode: Text.WordWrap
}
}