【问题标题】:How to change the colour of a row in the TableView of QML on a mouse event?如何在鼠标事件上更改 QML 的 TableView 中一行的颜色?
【发布时间】:2020-12-12 16:16:55
【问题描述】:

因此,当用户点击一行时,该行的颜色应该会发生变化。 这是我尝试过的。它不起作用。

这里table 是我的QML TableView 的ID。

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

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

【问题讨论】:

  • 如果您将onClicked 处理程序添加到您的MouseArea,它会被调用吗? (在里面放一个打印语句。)

标签: javascript qt qml qt5


【解决方案1】:

解决方案

styleData.selected代替styleData.row

示例

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

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

结果

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

选中第二行。

选择最后一行。

【讨论】:

  • 太棒了!有 Qt Quick Controls 2 的解决方案吗?看起来版本 1 在 Qt 5.11 中已被弃用,并在 Qt 6.0 中被删除。新的TableView 似乎更难做这些基本的事情。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-18
  • 2020-05-19
  • 1970-01-01
  • 2011-04-04
  • 1970-01-01
  • 2021-05-18
  • 1970-01-01
相关资源
最近更新 更多