Home > OS >  Changing the color of the switch in QML
Changing the color of the switch in QML

Time:08-25

I want the color to be green when the switch is on and red when it is off. I also want to write "On" in it when the switch is on and "Off" when it is off. How can I do it? Currently, my code is as follows:

 Rectangle{
        border.width: 2
        border.color: "black"
        id:rectangle_gps_l1_deger
        Layout.alignment: Qt.AlignCenter
        Layout.preferredWidth: mainWindow.width/8
        Layout.preferredHeight: mainWindow.height/22
        Layout.margins: -3
        Layout.fillWidth: true
        color:row_even
        ColumnLayout {
            anchors.centerIn: parent
            Switch {
                id:switch_rectangle_gps_l1_deger
                text: qsTr("")
                Material.accent: Material.Green

            }

        }
    }

CodePudding user response:

you should check its state by using if and else

import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
import QtQuick.Controls.Material 2.15

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Switch")

    Switch {
        id: switch1
        x: 272
        y: 200
        width: 101

        text: qsTr("off")
        Material.accent: Material.Green

        onToggled:
        {
            if(checked)
            {
                switch1.text= qsTr("on")

            }
            else
            {
                switch1.text= qsTr("off")

            }

        }

    }

}

enter image description here

enter image description here

  • Related