QML按钮更改文本颜色

时间:2016-11-26 21:47:53

标签: qt qml qtquick2 qtquickcontrols2

我是QML的新手,我想个性化我的按钮。我成功地改变了背景的颜色和边框颜色。但我根本没有成功改变按钮文字的颜色。我看到我们不再使用“风格”改变风格而是“背景”,我不了解它的一切。

感谢您的帮助。

Button {
        id: buttonAC
        text: qsTr("AC")
        Layout.fillHeight: true
        Layout.fillWidth: true

        background: Rectangle {
            border.color: "#14191D"
            color: "#24292f"
            // I want to change text color next
        }

        /*Text {
            text: qsTr("AC")
            color: "#F54035"
        }*/
}

4 个答案:

答案 0 :(得分:7)

根据doc

import QtQuick 2.6
import QtQuick.Controls 2.1

Button {
    id: control
    text: qsTr("Button")

    contentItem: Text {
        text: control.text
        font: control.font
        opacity: enabled ? 1.0 : 0.3
        color: control.down ? "#17a81a" : "#21be2b"
        horizontalAlignment: Text.AlignHCenter
        verticalAlignment: Text.AlignVCenter
        elide: Text.ElideRight
    }

    background: Rectangle {
        implicitWidth: 100
        implicitHeight: 40
        opacity: enabled ? 1 : 0.3
        border.color: control.down ? "#17a81a" : "#21be2b"
        border.width: 1
        radius: 2
    }
}

答案 1 :(得分:3)

我发现的两种最快的方法是使用以下未记录的属性:

Button {
     ....
     palette.buttonText: "white"
}

在用户交互期间自定义文本颜色时,要走得更远,这里是Button源代码中的三进制,后面是要进行相应设置的属性列表:

color: control.checked || control.highlighted ? control.palette.brightText :
           control.flat && !control.down ? (control.visualFocus ? control.palette.highlight : control.palette.windowText) : control.palette.buttonText

属性:

control.palette.brightText
control.palette.highlight
control.palette.windowText
control.palette.buttonText

第二个肮脏的技巧是使用onCompleted插槽,如下所示:

Button {
     id: control
     ....
     Component.onCompleted: {
          control.contentItem.color = "white";
     }
}

答案 2 :(得分:2)

如果您只想更改文本颜色,可以在Button中使用html字体样式会更好。这将保留其他Item之类的按钮图标:

Button
{
    //...
    text: "<font color='#fefefe'>" + moudle + "</font>"
    font.family: "Arial"
    font.pointSize: 24
    //...
}

答案 3 :(得分:0)

如果要使用QML样式,还有另一种方法。

Button {
    id: goToParenFolder
    text: "Hi"
    flat: true
    Material.foreground: "red"
}

此按钮的文本将为红色,其他按钮将采用“材质样式”颜色。