[Development] [QML] ListModel discards item's method
Nurmi J-P
jpnurmi at digia.com
Sat May 3 21:30:47 CEST 2014
On 03 May 2014, at 16:04, Ben Lau <xbenlau at gmail.com> wrote:
> Hi,
>
> I have few questions about the implementation of ListModel and the design principle about using models with object in QML application.
>
> I would like to use a model class to hold a list of item (or C++ QObject ) with custom methods / slot functions. However, I found that after the item/QObject is appended to the ListModel, then access the model to get back the object. The associated method will become a property value and not able to call.
>
> The following code demonstrates the problem:
>
> import QtQuick 2.0
> import QtTest 1.0
>
> TestCase {
>
> Item {
> id : testItem
> property string name : "testObject"
> function testMethod() {
> return -1;
> }
> }
>
> ListModel {
> id : listModel
> }
>
> function test_ListModel() {
> listModel.append(testItem);
> compare(listModel.count , 1);
>
> var item = listModel.get(0);
>
> compare(item !== testItem, true); // They are not the same object
> compare(item.name , "testObject");
>
> expectFail("","The testMehod() should be a function but now it becomes a property");
> compare(typeof item.testMethod , "function");
> }
>
> }
Hi,
Notice that ListModel::append() takes a JS dictionary, and get() returns it. Make it something like:
listModel.append({"item": testItem});
var obj = listModel.get(0);
compare(obj.item, testItem);
--
J-P Nurmi
More information about the Development
mailing list