简体   繁体   English

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

[英]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 .这里的table是我的 QML TableView的 id。

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

Solution解决方案

Instead of styleData.row use styleData.selected .而不是styleData.row使用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 选定的第 2 行

With the second row selected.选择第二行。

TableView 选定的第 3 行

With the last row selected.选择最后一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM