How to change the colour of a row in the TableView of QML on a mouse event?

So, when a user clicks on a row, the colour of that row should change. This is what I have tried. It doesn’t work.

Here table is the id of my QML TableView.

Let default color be blue and on click it should change to red.

   rowDelegate:
            Rectangle
            {
                id: rowDel
                color:
                {
                    var activeRow = table.currentRow === styleData.row;
                                (activeRow ? mouse_area.pressed ? "red" : "blue" : "white")
                }

                border.width: 1
                height: 52
                width: 2000

                MouseArea
                {
                    id: mouse_area
                    anchors.fill: parent
                }
            }

Answer

Solution

Instead of styleData.row use styleData.selected.

Example

Here is an example I wrote for you to demonstrate the proposed solution:

import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 1.4

Window {
    width: 320
    height: 200
    visible: true
    title: qsTr("TableView")

    ListModel {
        id: libraryModel
        ListElement {
            title: "A Masterpiece"
            author: "Gabriel"
        }
        ListElement {
            title: "Brilliance"
            author: "Jens"
        }
        ListElement {
            title: "Outstanding"
            author: "Frederik"
        }
    }

    TableView {
        id: table

        anchors.fill: parent
        model: libraryModel

        rowDelegate: Rectangle {
            color: styleData.selected ? "red" : "blue"
            width: 2000
            height: 40
            border.width: 1
        }

        TableViewColumn {
            role: "title"
            title: "Title"
            width: 100
        }

        TableViewColumn {
            role: "author"
            title: "Author"
            width: 200
        }
    }
}

Result

The provided example produces the following result:

TableView selected row 2

With the second row selected.

TableView selected row 3

With the last row selected.