0

I have a Model that exposes some properties like that:

class KeyValueModel : public QObject
{
  Q_PROPERTY(QVariant key READ key WRITE setKey NOTIFY keyChanged)
  Q_PROPERTY(QString value READ value WRITE setValue NOTIFY valueChanged)
  Q_OBJECT

  public:    
    KeyValueModel(const QVariant& key, const QString& value);

    QVariant key() const { return m_key; }
    void setKey(const QVariant& key) { m_key = key; emit keyChanged(); }

    QString value() const { return m_value; }
    void setValue(const QString& value) { m_value = value; emit valueChanged(); }

  signals:
    void keyChanged();
    void valueChanged();

  private:
    QVariant m_key;
    QString m_value;
};

Then I have a proxy that exposes a QList<KeyValueModel*> like that:

class Proxy : public QObject
{
  Q_OBJECT
  Q_PROPERTY(QList<KeyValueModel*> data READ data NOTIFY dataChanged)

  public:
    Proxy();

    void setData(const QList<KeyValueModel*>& data) { m_data = data; emit dataChanged(); }

    Q_INVOKABLE void changeData(); //this function call setData(new objects)

  signals:
    void dataChanged();

  private:
    const QList<KeyValueModel*> data();

  private:
    QList<KeyValueModel*> m_data;
};

When should I delete m_data?
If I delete the old data in setData() before notifying qml that data has changed qml points to delete objects and the app can crash, is it right?
Can i save m_data like QList<QSharedPointer<KeyValueModel>> m_data?

Fausto01
  • 171
  • 14
  • I have not experienced problems with such structures. However, this does look an awfull lot like QVariantMap, have you considered using that instead? I think the integration on QML side is much better than with QList – Amfasis Mar 11 '22 at 10:20
  • Yes, but what if I need another property in the future? – Fausto01 Mar 11 '22 at 10:30
  • That's a valid point. I don't have much experience with shared pointers directly in QML. But also, I did not have problems with similar structures as the above code. Be sure to properly delete the old list, see this recent question: https://stackoverflow.com/questions/71322191/memory-management-for-list-of-qobject-results-in-cannot-read-property-x-of-nul/71337384#71337384 – Amfasis Mar 11 '22 at 11:16

0 Answers0