QML ListModel and custom function property

2.9k Views Asked by At

I want to write tuned version of TableView (TableView.qml in Qt package). I have ColumnDescriptor.qml with column definition:

Item {
    property string title
    property var formatDelegate: null

    .... (other property definition)

    function format(val) {
        if (formatDelegate != null)
            return formatDelegate(val);
        else
            return val;
    }
}

The above code defines set of properties and fuction format(val), that calls for format value if formatDelefate was set.

In the main table I use list to store predefined columns definition (temporaly) and ListModel to store final columns definition ( the latter is more useful than list in remaining implementation)

list example:

 property list<ColumnDescriptor> colDefines: [
    ColumnDescriptor { 
        title: qsTr("col1")  
    },
    ColumnDescriptor { 
        title: qsTr("col2")
        formatDelegate: function(val) { return "!" + val}
    }
]

Filling ListModel (id: columnModel):

Component.onCompleted: {
    for(var i = 0; i < colDefines.length; ++i)
    {
        var col = colDefines[i];
        ...(some calculation)
        columnModel.append(col);
    }
}

All looks fine, but when I try to call format from model item, Qt sends me the following error

Property 'format' of object QQmlDMListAccessorData(0x8e3bf78) is not a function

Example of calling format:

Repeater {
    model: columnModel
    Text {
        text: model.format([SOME USEFUL DATA])
    }
}

On the other hand, if I call format directly from list it works well. So my question here is how to fill model in a way that the format or other function will work correctly when being called from model?

2

There are 2 best solutions below

1
On

Try this

Repeater {
    model: columnModel
    Text {
        text: columnModel[index].format([SOME USEFUL DATA])
    }
}
0
On

For QtQuick2 this should work

formatDelegate = [function(val) { return "!" + val}]
formatDelegate[0]("some text")

but you could also use an overriding technique:

Item {
    function formatDelegate(val) {
       return val;
    }

    function format(val) {
       return formatDelegate(val);
    }
}
ColumnDescriptor { 
    function formatDelegate(val) {
       return "!" + val
    }
}

This way Item.format() should call "return val" as default and "!"+val for ColumnDescriptor given that ColumnDescriptor is derived from Item.