0
votes

I am relatively new to QT and QML in general. I have seen examples where it is possible to change the the color of some outside object (such as text) when pressing a rectangle. However, I would like to do something related, but different.

Setup:

I want to have a grid of rectangles. Let's say 5x5 grid. All of these rectangles can be of Blue color. Size is not important.

Example:

  • If I press the Rectangle at (0,0) its color should change to Red.
  • If I press the Rectangle at (0,1) its color should change to Red as well.
  • If a Rectangle is Red and I press it, it should revert back to Blue.

Ideally, I would also like to know which Rectangles are Red and which are Blue. Hopefully I can figure that out later on. For now, it would be really useful if someone could help me start with just changing the color. It would be very helpful to just know how to change the color of a single Rectangle when it is pressed. Thank you in advance!

1
First example on this page doc.qt.io/qt-5/qml-qtquick-mousearea.html. You can learn a lot from the welcome examples which are included with your Qt installation.Mark Ch
Next look up gridlayout or gridview to make your grid. Welcome to Qt and QML. I hope you enjoy it.Mark Ch
@MarkCh, thanks for the information. That example was super helpful. No idea why I couldn't find that on my own (little embarrassing). If I want to press and hold and have this also change their colors. Would I need to look into dragging?Knoose
I think you would need to use onEntered as well as onClicked. I have not tried it thoughMark Ch
FYI, the down vote was not me, but I suspect the reasoning was probably either lack of research or overly broad (meaning not very specific, requiring answerer to start from scratch with no starting point and write a small program). Could be avoided in future by trying to write some code of your own, and posting it up in the question.Mark Ch

1 Answers

0
votes
Item {
id: root
width: 500
height: 500

Column {
    Repeater {
        id: column
        model: 5
        Row {
            Repeater {
                id: row
                model: 5
                Rectangle {
                    id: rect
                    property bool isBlue: true
                    width: 100
                    height: 100
                    color: isBlue ? "blue" : "red"
                    border.color: "white"
                    border.width: 5
                    Text {
                        font.pixelSize: 15
                        anchors.centerIn: parent
                        text: rect.isBlue ? "blue" : "red"
                        color: "white"
                    }

                    MouseArea {
                        anchors.fill: parent
                        onClicked: {
                            rect.isBlue = !rect.isBlue
                        }
                    }
                }
            }
        }
    }
}

}