How do I correctly handle mouse events in a QML TableView with overlapping mouse areas?

与世无争的帅哥 提交于 2019-12-06 00:07:07

If it is only the the selection you want to achive you can set the selection manually:

TableView {
    id: tv
    itemDelegate: Item {
        Text {
            anchors.centerIn: parent
            color: styleData.textColor
            elide: styleData.elideMode
            text: styleData.value
        }
        MouseArea {
            id: ma
            anchors.fill: parent
            onPressed: {
                tv.currentRow = styleData.row
                tv.selection.select(styleData.row) // <-- select here.
            }
            onClicked: {
                console.log(styleData.value)
            }
        }
    }

    TableViewColumn {
        role: 'c1'
        title: 'hey'
        width: 100
    }
    TableViewColumn {
        role: 'c2'
        title: 'tschau'
        width: 100
    }
    model: lm
}

Right now I only select. But you can write your very own selection/deselection-logic.

You might also map from the TableView.__mouseArea to the delegate.

import QtQuick 2.7
import QtQuick.Controls 1.4

ApplicationWindow {
    id: appWindow
    width: 1024
    height: 800
    visible: true

    ListModel {
        id: lm
        ListElement { c1: 'hallo1'; c2: 'bye' }
        ListElement { c1: 'hallo2'; c2: 'bye' }
        ListElement { c1: 'hallo3'; c2: 'bye' }
        ListElement { c1: 'hallo4'; c2: 'bye' }
        ListElement { c1: 'hallo5'; c2: 'bye' }
        ListElement { c1: 'hallo6'; c2: 'bye' }
        ListElement { c1: 'hallo7'; c2: 'bye' }
        ListElement { c1: 'hallo8'; c2: 'bye' }
        ListElement { c1: 'hallo9'; c2: 'bye' }
    }

    TableView {
        id: tv
        itemDelegate: Item {
            id: mydelegate
            signal doubleclicked()
            onDoubleclicked: console.log(styleData.value)
            Text {
                anchors.centerIn: parent
                color: styleData.textColor
                elide: styleData.elideMode
                text: styleData.value
            }

            Connections {
                target: tv.__mouseArea
                onDoubleClicked: {
                    // Map to the clickposition to the delegate
                    var pos = mydelegate.mapFromItem(tv.__mouseArea, mouse.x, mouse.y)
                    // Check whether the click was within the delegate
                    if (mydelegate.contains(pos)) mydelegate.doubleclicked()
                }
            }
        }

        TableViewColumn {
            role: 'c1'
            title: 'hey'
            width: 100
        }
        TableViewColumn {
            role: 'c2'
            title: 'tschau'
            width: 100
        }
        model: lm
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!