[Development] [QML] ListModel discards item's method
Ben Lau
xbenlau at gmail.com
Sun May 4 12:32:19 CEST 2014
On 4 May 2014 03:30, Nurmi J-P <jpnurmi at digia.com> wrote:
> 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
>
>
Thank for your reply. The solution works! And that inspired me for another
alternative solution:
import QtQuick 2.0
import QtTest 1.0
TestCase {
Item {
id : testItem
property string name : "testObject"
property var object : this
function testMethod() {
return -1;
}
}
ListModel {
id : listModel
}
function test_ListModel() {
listModel.append(testItem);
compare(listModel.count , 1);
var item = listModel.get(0);
compare(typeof item.object.testMethod , "function");
compare(item.object.testMethod() , -1);
}
}
> _______________________________________________
> Development mailing list
> Development at qt-project.org
> http://lists.qt-project.org/mailman/listinfo/development
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/development/attachments/20140504/2ccc589c/attachment.html>
More information about the Development
mailing list