QML 自定义Button控件与Button 样式的实现

1.自定义控件

新建一个QML文件,命名为MyselfButton.qml,写如入代码

import QtQuick 2.0
 
Rectangle {
    id: btn;
    width: 200;
    height: 40;
    color: "red";
    property string btnName: "";
    signal myclicked();
    Text {
        id: name
        text: btnName;
        color: "white";
        anchors.centerIn: parent;
    }
 
    MouseArea
    {
        id: mos;
        anchors.fill: parent;
        hoverEnabled: true;//控制开关,如果开启,entered与exited信号会接收,否则不会接收
        onClicked:
        {
            myclicked();
        }
 
        onEntered:
        {
            btn.color = "blue";
        }
 
        onExited:
        {
            btn.color = "red";
        }
    }
 
}
这样就做成了一个控件,调用的方式如下:
  MyselfButton
    {
        id: btn;
        btnName: "确定";
        onMyclicked:
        {
            console.log("--------------");
        }
    }

第二种方式:用ButtonStyle样式

在引用buttoStyle样式的时候

    import QtQuick.Controls 1.4
    import QtQuick.Controls.Styles 1.4
    Button {
        id: btn;
        width: 200;
        height: 30;
         style: ButtonStyle {
             background: Rectangle {
                 implicitWidth: 100
                 implicitHeight: 25
                 border.width: control.activeFocus ? 2 : 1
                 border.color: "#888"
                 radius: 4
                 color: control.hovered ? "blue" : "red";
 
             }
             label:Text
             {
                 text:"确定";
                 color:"white";
                 verticalAlignment: Text.AlignVCenter;//设置字体垂直居中
                 horizontalAlignment:Text.AlignHCenter;//设置字体水平居中
             }
         }
     }

猜你喜欢

转载自blog.csdn.net/qq_16628589/article/details/81842390