Home > OS >  How to change the text color of only the cell that is clicked on a GridView in QML?
How to change the text color of only the cell that is clicked on a GridView in QML?

Time:08-25

In a GridView, I want to change the color of the text that is on the cell that is clicked.

The code below changes the color of the text contained in all the cells, not only the one that was clicked.

What needs to be done to change only the text of the cell that is clicked?

property string textColor: "black";

GridView {
        id: gridAmplitudeValues
        x: 20; y: 63;
        width: 544; height: 227;
        cellWidth: 136; cellHeight: 38
        interactive: false
        
        Component {
            id: cellContent

            Rectangle {
                width: 117; height: 38;
                color: "lightgreen";
                Text {
                    id: textValue;
                    text: "text";
                    color: textColor;
                }
                
                MouseArea {
                    anchors.fill: parent
                    onClicked:{
                        gridAmplitudeValues.currentIndex = model.index;
                        textColor = "red";
                    }
                }
            }
        }

        model: 24
        delegate: cellContent
}

CodePudding user response:

The problem is the textColor property is defined outside the grid. So when you change it, it affects all the cells. You can fix this by using some other state property, and changing the color of the text based on that state.

property string textColor: "black";

GridView {
    Component {
        id: cellContent

        // Store the clicked state in a property
        property bool cellClicked: false

        Rectangle {
            Text {
                // Make the text color dependent on the clicked state
                color: cellClicked ? "red" : textColor
            }
                
            MouseArea {
                onClicked:{
                    // Update the clicked state
                    cellClicked = !cellClicked;
                }
            }
        }
    }

    model: 24
    delegate: cellContent
}

UPDATE:

To make it so only one item is red at a time, you can make use of the GridView's currentIndex property.

GridView {
    id: gridAmplitudeValues

    Component {
        id: cellContent

        Rectangle {
            Text {
                // Make the text color dependent on the currentIndex
                color: gridAmplitudeValues.currentIndex === index ? "red" : textColor
            }

            MouseArea {
                onClicked:{
                    // Update the currentIndex
                    gridAmplitudeValues.currentIndex = index;
                }
            }
        }
    }

    model: 24
    delegate: cellContent
}
  • Related