在QML中更改按钮上单击窗口的背景颜色

时间:2019-06-17 04:32:54

标签: qt qml

我正在开发qml项目,因为我想添加更改背景颜色的功能..

为此,我创建了一个包含项目{red,blue,white}的组合框,并创建了一个更新按钮以在用户选择红色项目并单击更新背景颜色更改为红色时更新颜色,我该怎么做? >

Button {
            id: button1
            x: 284
            y: 95
            width: 114
            height: 34
            text: qsTr("Update")


            contentItem: Text {

                   font: control.font
                   opacity: enabled ? 1.0 : 0.3
                   text: "Update"
                   //Font.pixelSize:15
                   horizontalAlignment: Text.AlignHCenter
                   verticalAlignment: Text.AlignVCenter
                   elide: Text.ElideRight
               }
            background: Rectangle {
                       id: myRectId1
                       color: Colorchange.Rectange_Color
                       radius: 8
                   }
            onHoveredChanged: hovered ? myRectId1.opacity = 1 :
            myRectId1.opacity = .80;
            MouseArea {
                   id: mouseAreaScanbtn
                   anchors.fill: parent
                   hoverEnabled: true;
                   onEntered: { myRectId1.border.width = 2 }
                   onExited: { myRectId1.border.width = 1 }
                   onClicked: {
      //i want to add some code here to change background color
      // i tried 
            //window.color:combobox.currantindex()
}
               }
        }

1 个答案:

答案 0 :(得分:0)

您只需使用ComboBox Qml类型,如下所示:

ComboBox {

        currentIndex: -1
        width: 200
        model: [ "white", "blue" , "red" ]
        onCurrentIndexChanged:{

             background.color=model[currentIndex]

        }


}

或者如果要在用户单击按钮后更新背景色,则应保存用户在属性中选择的颜色,然后在按钮的onClicked中使用此颜色:

Item {
    id:root 
    property  var SelectedColor
    ComboBox {

        currentIndex: -1
        width: 200
        model: [ "white", "blue" , "red" ]
        onCurrentIndexChanged:{

             SelectedColor=model[currentIndex]

        }



}