如何在 Qt6 中悬停按钮时更改 QML 按钮的文本颜色

问题描述 投票:0回答:2

Button悬停时,如何更改Button的文本颜色?我不想画矩形。

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
    }
}

我尝试使用

color: button.down
,但它在 Button 的文本周围绘制了一个矩形。

qt button qml hover textcolor
2个回答
3
投票

最佳实践方法是使用调色板。 它更短、更干净、更简单。

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

也如 @JarMan 所提到的并基于 文档

项目将显式调色板属性从父级传播到子级。如果您更改项目调色板上的特定属性,该属性会传播到该项目的所有子项,从而覆盖该属性的任何系统默认值。

可以将调色板分配给嵌套的项目组,如以下示例所示:

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

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

1
投票

通过设置按钮的

contentItem

    Button {
        id: button
        text: "Button"

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

    }
© www.soinside.com 2019 - 2024. All rights reserved.