Skip to content
KerwinKoo edited this page Dec 27, 2015 · 2 revisions

Qt5.2 QML ButtonStyle

简介

要使用 ButtonStyle 需要引入 QtQuick.Controls.Styles 1.1 ButtonStyle 类有 backgroundcontrollabel 三个属性。

我们通过重写 background 来定制一个按钮。

control 属性指向应用 ButtonStyle 的按钮对象,你可以用它访问按钮的各种状态。

label 属性代表按钮的文本,如果你看它不顺眼,也可以替换它。

background 实际是一个 Component (组件) 对象

例:

import QtQuick 2.0
import QtQuick.Controls 1.1
import QtQuick.Controls.Styles 1.1

Rectangle {
    width: 300;
    height: 200;
    Button {
        text: "Quit";
        anchors.centerIn: parent;
        style: ButtonStyle {		//为button的style对象指定ButtonStyle对象(ButtonStyle的实现)
            background: Rectangle {	//重写background属性,目的是通过Rectangle对象来定义按钮背景
                implicitWidth: 70;	//重定义建议宽度和高度
                implicitHeight: 25;
                border.width: control.pressed ? 2 : 1;	//修改按下时边框宽度。control是实际按钮的引用
                border.color: (control.hovered || control.pressed) ? "green" : "#888888";
                     //hovered:鼠标只放上而未点击。pressed:鼠标点击

            }
        }
    }
}

代码说明

通过给 style 对象指定一个 ButtonStyle 对象来定制 Button 的风格。这个就地实现的 ButtonStyle 对象,重写了 background 属性。

通过 Rectangle 对象来定义按钮背景。我定义了背景的建议宽度和高度,根据按钮的 pressed 属性( control 是实际按钮的引用 )来设置背景矩形的边框粗细,而边框颜色则随着按钮的 hovered 和 pressed 属性来变化。

ButtonStyle定义同类风格

import QtQuick 2.0
import QtQuick.Controls 1.1
import QtQuick.Controls.Styles 1.1

Rectangle {
    width: 300;
    height: 200;

    Component{	//单独定义一个组件(相当于该组件的定义和声明)
        id: btnStyle;
        ButtonStyle {
            background: Rectangle {
                implicitWidth: 70;
                implicitHeight: 25;
                color: "#DDDDDD";
                border.width: control.pressed ? 2 : 1;
                border.color: (control.hovered || control.pressed) ? "green" : "#888888";
            }
        }
    }

    Button {
        id: openButton;
        text: "Open";
        anchors.left: parent.left;
        anchors.leftMargin: 10;
        anchors.bottom: parent.bottom;
        anchors.bottomMargin: 10;
        style: btnStyle;//定义style时,直接指定btnStyle组件id(该组件的实现)
    }

    Button {
        text: "Quit";
        anchors.left: openButton.right;
        anchors.leftMargin: 6;
        anchors.bottom: openButton.bottom;
        style: btnStyle;
    }
}

[[TOC]]

Clone this wiki locally