1
votes

I'm having a difficult time explaining my problem, so I'm just going to make it as simple and hope it does the job. I'm using Qt5 with QtQuick 2.0.

I've created a MyListModel class that inherits from QAbstractListModel, and holds items of type MyListItem. I use it in a QML ListView as a model: myListModel, and the delegate displays a quantity property from MyListItem, in a lovely TextInput box. Everything works fine.

However, when I change the quantity value from the delegate, the items in the model aren't updated. I know they're not updated, because my setQuantity(long desired_quantity) function, a member of MyListItem, does not run. Long story short, I can't figure out how to actually call the setQuantity function from within the delegate. I can do it manually by adding Q_PROPERTY(long quantity READ quantity WRITE setQuantity) to MyListItem, and then using setContextProperty() to expose a MyListItem myTemp object to QML, and then calling myTemp.quantity = 10. But clearly, if the delegate can't write to the quantity property (it can only read from it), it's not doing the job.

Can somebody point me in the right direction? I feel like I've tried everything the Qt designers could have possibly expected, and I get nothing. And I can't find any documentation that clearly addresses my issue.

1

1 Answers

3
votes

The TextInput box will not update your c++ model automatically, you have to do this by yourself. You can do this by adding a slot or Q_INVOKABLE method to you model:

//add a slot to you model
public slots:
 setDataInModel(const int index, const QVariant &value);
//or add Q_INVOKABLE method:
public:
 Q_INVOKABLE setData(const int index, const QVariant &value);

You have to implement one of these methods so that it changes the appropriate data row in your model. Do not forget to call the dataChanged method inside of the method after update. You then have to call these methods from QML delegate manually when the TextInput is updated:

onAccepted: {
  model.setDataInModel(index, text)
}

Here index is a property that is defined in each delegate and text is the text from your TextInput.