如何在使用qml单击时将背景图像更改为按钮中的另一个背景图像

How to change a background image to another background image in button while clicking using qml

我需要在使用 qml 单击时将 按钮 的背景图片从一张图片更改为另一张图片。

这是我的代码:

Button{
    id:bu
    x: 121
    y: 40
    iconSource: "q.png"
    activeFocusOnPress: false
    opacity: 1
    checkable: true
    checked: true
    Layout.minimumWidth: 100
    Layout.minimumHeight: 100
}

上面的代码只设置了背景图片,但是,我需要在 onClicked 事件或使用 qml2.4 的任何其他事件上更改我的背景图片。

如果您查看 Button QML 类型,您会发现 clicked() 是您单击按钮时发出的信号。我们可以在 qml 中的插槽 onClicked 中捕获此信号,并且可以更改按钮的 iconSource 属性

代码将是这样的:

    Button {
    id: bu
    x: 121
    y: 40
    iconSource: "q.png"
    activeFocusOnPress: false
    opacity: 1
    checkable: true
    checked: true
    Layout.minimumWidth: 100
    Layout.minimumHeight: 100

    onClicked: {
                bu.iconSource = "index.png"
            }

}

通过这种方式,您可以将按钮的屏幕背景图像从一个图像更改为另一个图像。

更新: 根据您的要求,您可以使用以下代码:

property bool bImgChange: true

Button {
id: bu
x: 121
y: 40
iconSource: "q.png"
activeFocusOnPress: false
opacity: 1
checkable: true
checked: true
Layout.minimumWidth: 100
Layout.minimumHeight: 100

    onClicked: {
        if ( bImgChange == true )
        {
            bu.iconSource = "index.png"
            bImgChange = false
        }
        else
        {
            bu.iconSource = "q.png"
            bImgChange = true
        }
    }
}

您可以使用用户定义的 属性 bImgChange 并可将其用于检查条件。 您的条件将不起作用,因为 bu.iconSource 将为您提供图像文件所在的完整路径。例如。 /home/user/some/path/q.png 并且您正在将其与 if 条件中的字符串 q.png 进行比较。

希望对您有所帮助。