QML TableView rowDelegate styleData.row not defined

半世苍凉 提交于 2020-12-31 17:20:17

问题


I am trying to create a custom row delegate for a TableView. according to the Documentation, the rowDelegate should have access to a property called styleData.row. However, when I'm try to access this property, it is undefined. I used the debugger to check whats inside the styleData, and the row is missing:

My code is very simple:

TableView {
    width: 500//DEBUG
    height: 300//DEBUG

    model: ListModel {
        ListElement {
            lectureName: "Baum1"
        }
        ListElement {
            lectureName: "Baum2"
        }
        ListElement {
            lectureName: "Baum3"
        }
        ListElement {
            lectureName: "Baum4"
        }
    }

    rowDelegate: HeaderRowDelegate {//simply a Rectangle with an in property called "modelRow"
        id: rowDelegate
        modelRow: {
            var data = styleData;
            return data.row;
        }
    }

    TableViewColumn {
        id: c1
        role: "lectureName"
        title: "TEST"
    }
}

回答1:


You don't have to assign it yourself: as the HeaderRowDelegate component is assigned to the rowDelegate property of the TableView, your component has already access to the styleData.row property.

Here's an example:

main.qml

import QtQuick 2.4
import QtQuick.Layouts 1.1
import QtQuick.Controls.Styles 1.2
import QtQuick.Controls 1.3

ApplicationWindow {
    id: app
    title: qsTr("Test")
    width: 800
    height: 600

    TableView {
        width: 500//DEBUG
        height: 300//DEBUG

        model: ListModel {
            ListElement {
                lectureName: "Baum1"
            }
            ListElement {
                lectureName: "Baum2"
            }
            ListElement {
                lectureName: "Baum3"
            }
            ListElement {
                lectureName: "Baum4"
            }
        }

        rowDelegate: RowDel {}        

        TableViewColumn {
            id: c1
            role: "lectureName"
            title: "TEST"
        }
    }
}

Now the row delegate, RowDel.qml

import QtQuick 2.4

Rectangle {
    id: rowDel
    color: "blue"
    height: 60

    readonly property int modelRow: styleData.row ? styleData.row : 0

    MouseArea {
        anchors.fill: parent
        onClicked: {
            console.log("[!] log: " + modelRow);
        }
    }       
}

The important thing here is that you can reference styleData.row directly from your component (obliviously as long as you use this precise component as a row delegate).

As an example, if you click on each tableview row, you should see the correct row number displayed in the console log:

qml: [!] log: 0
qml: [!] log: 1
qml: [!] log: 2
qml: [!] log: 3


来源:https://stackoverflow.com/questions/33958231/qml-tableview-rowdelegate-styledata-row-not-defined

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!