How to change the text color of a QML Button when the Button is hovered in Qt6

144 Views Asked by At

How can I change the text color of the Button when the Button is hovered? I don't want to draw a rectangle.

Button {
    id:button
    x: 58
    y: 246
    width: 188
    height: 34
    onClicked: classA.newGameWindow()

    text: qsTr("New Game")

    background: Rectangle {
        opacity: enabled ? 1 : 0.3
        color: "transparent"
    }

    font.family: "Inria Serif"
    font.pixelSize: 26

    Text {
       id: new_Game
       color: "white"
       horizontalAlignment: Text.AlignLeft
       verticalAlignment: Text.AlignTop
       wrapMode: Text.Wrap
       font.weight: Font.Normal
    }
}

I tried to use color: button.down but it draws me a rectangle around the text of the Button.

2

There are 2 best solutions below

1
Jürgen Lutz On BEST ANSWER

By setting the contentItem of your button:

    Button {
        id: button
        text: "Button"

        contentItem: Text {
            text: button.text
            color: button.hovered ? "green" : "red"
        }

    }
1
smr On

A best practice approach would be to use palettes. It is shorter, cleaner, and simpler.

Button { 
    text: 'Example text' 
    palette.buttonText: hovered ? 'red' : 'blue' 
}

Also as mentioned by @JarMan and based on the documentation:

Items propagate explicit palette properties from parents to children. If you change a specific property on a items's palette, that property propagates to all of the item's children, overriding any system defaults for that property.

It is possible to assign a palette to a nested group of items, as shown in the following example:

Item {
    // The color will be assigned to all children.
    palette.buttonText: 'maroon'

    Button { /* ... */ }
    Item {
        Button { /* ... */ }
        Item { 
            Button { /* ... */ }
            Button { /* ... */ }
            // ...
        }   
    }
}