简体   繁体   中英

Storing a Q_GADGET in a ListModel, it “forgets” about its methods

I have a error queue (as a C++ class available as a context property) that can regularly give me a list of Error values, which is a Q_GADGET. The gadget has a set of properties, among them extTimeStamp which is also a custom Q_GADGET of type JSDate64 .

So when I get errors, I push the timestamp and messages into a ListModel like this

function collectErrors() {
   if( errorQueueController.drainable ) {
      for(const error of errorQueue.popErrors()) {
         console.log("Time: " + error.extTimeStamp.asDateTime())
         errorsModel.append({extTimeStamp: error.extTimeStamp, extMessage: error.extMessage})
      }
   }
}

As can be seen, I log the timestamp before the append and it is also shown in the Text delegate, which I connected to the ListModel

delegate: Text {
   color: "white"
   text: model.extTimeStamp.asDateTime() + ": " + model.extMessage
}

But as it turns out, I only see this in the debug output:

qml: Time: Fri Nov 4 00:43:01 2016 GMT+0100

qrc:/views/DummyView2.qml:352: TypeError: Property 'asDateTime' of object [object Object] is not a function

Even though it is the same value, somehow the properties are gone when queried from within the delegate, I also registered a string converter for my Q_GADGET, and it works at the time of append , but when I convert extTimeStamp to a string in the delegate, I just get [object Object] .

Further, I figured that if I enable dynamicRoles for the ListModel , everything works as expected. Since the performance is much worse with dynamicRoles , the Qt manual discourages from its use, unless it's absolutely required. But I don't understand what it has to do with that, since I'm not changing the data type of roles at all. The extTimeStamp role will always be my JSDate64 -Gadget!

// Why does it work with "dynamicRoles: true"?
ListModel { id: errorsModel; dynamicRoles: true }

You're assigning your Q_GADGET to a ListElement . ListElement s have the annoying feature of looking like they hold properties like any other QML object, but they're not properties. They're "roles", and they can only store constant data, like strings. (See docs ). So it must be automatically converting your Q_GADGET to something that it accepts, but is not really useful to you anymore. I'm not exactly sure why dynamicRoles would make it work. Maybe that allows it to be more loose with the type of objects that it stores.

It looks to me like a possible solution for you could be to store the date as a string in your model, instead of as an object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM