Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QML button change text color

I'm new in QML and i want to personalize my buttons. I succeed to change the background's color and border color. But I don't success at all to change the color of the button's text. I saw we don't use anymore "style" to change the style but "background" and I don't understand everything about it.

Thanks for your help.

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"
        }*/
}
like image 656
Lazyos Avatar asked Nov 26 '16 21:11

Lazyos


3 Answers

According to the 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
    }
}
like image 142
nAkhmedov Avatar answered Nov 19 '22 11:11

nAkhmedov


The two fastest ways I found were to either use the following undocumented property:

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

To go even further when customizing text colors during user interaction here is the ternary in the Button source code followed by a list of the properties to set accordingly:

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

Properties:

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

The second dirty hack would be to use the onCompleted slot as follows:

Button {
     id: control
     ....
     Component.onCompleted: {
          control.contentItem.color = "white";
     }
}
like image 33
emdou Avatar answered Nov 19 '22 11:11

emdou


If you just wanna change your text color, may you use html font style in your Button would be better. This will keeping other Item like button icon:

Button
{
    //...
    text: "<font color='#fefefe'>" + moudle + "</font>"
    font.family: "Arial"
    font.pointSize: 24
    //...
}
like image 6
Crawl.W Avatar answered Nov 19 '22 13:11

Crawl.W