自定义button样式

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
    }

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容