簡體   English   中英

如何獲取與在 QML 的 TableView 中單擊的行關聯的 ListElement?

[英]How to fetch the ListElement associated with the row which is clicked in a TableView in QML?

我在 QML 中定義了一個TableView ,它顯然會有多行由ListModel填充。

我想獲取與雙擊的行關聯的ListElement

我將表視圖的rowDelegate定義為:

rowDelegate: Rectangle {
    color: "#D3D3D3"
    height: 30
    MouseArea {
        anchors.fill: parent
        onDoubleClicked: {
            console.log("table view row clicked...")
            // How to fetch the ListElement associated with the row
            // and return it for use by another module?
        }
    }
}

我的評論非常強調我在尋找什么。

在您的委托的 scope 中,您可以使用model偽屬性來獲取關聯的ListElement (或通過該委托顯示的任何其他數據)。 您可能會將其視為對原始數據項的引用。 它具有ListElement的所有屬性(例如textcolor等)以及index屬性(ListModel 或任何其他模型中的項目索引)。

您甚至可能不需要MouseArea來處理委托中的點擊。

TableView已經有一個doubleClicked信號,您可以使用該信號從單擊的行索引中檢索 model 數據:

TableView {
    model: ListModel {
        ListElement {
            name: "name 1"
        }
        ListElement {
            name: "name 2"
        }
    }

    TableViewColumn {
        title: "name"
        delegate: Text {
            text: model.name
        }
    }

    rowDelegate: Rectangle {
        color: "#D3D3D3"
        height: 30
        // no MouseArea
    }

    // handle the click directly in TableView
    onDoubleClicked: {
        const element = model.get(row)
        console.error("doubleClicked on", element.name)
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM