如何在鼠标事件中更改 QML TableView 中一行的颜色?

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

因此,当用户单击某行时,该行的颜色应该会发生变化。 这是我试过的。没用。

这里table是我QML的idTableView

让默认颜色为蓝色,点击它应该变为红色。

   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
                }
            }

解决方案

而不是 styleData.row 使用 styleData.selected.

例子

这是我为您编写的示例,用于演示建议的解决方案:

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
        }
    }
}

结果

提供的示例产生以下结果:

选择了第二行。

选择了最后一行。