0
votes

I'm new to Qt, and have written a basic application which has one class which inherits from QObject and is bound to a QML file.

I now want that class to contain a Vector of objects (let's say from a class Customers), which contains some data, such as a QString for name, etc.

To make life easier I'll create these objects manually in main, and place some text fields in my QML file.

I now want to be able to bind specific objects to specific text fields in the QML file, such that when a value changes, the value in the text field updates.

How can this be done? It looks like QML statically calls methods of the classes it's bound to, instead of on an assigned object.

I feel like QAbstractList may have some use here, but not too sure. Would rather not have to inherit from anything for my Customers class.

EDIT:

I think I may be able to do what I want with a QObjectList-based Model (https://doc.qt.io/qt-5/qtquick-modelviewsdata-cppmodels.html). I notice it says at the bottom that "There is no way for the view to know that the contents of a QList has changed. If the QList changes, it is necessary to reset the model by calling QQmlContext::setContextProperty() again."

Does this mean that if a value inside DataObject (such as name) changes, the model has to be reset, or only when the Qlist itself changes (i.e. new item added, or item deleted)? If the latter, I would think this should be fairly easy to maintain as I would only need to set the context property whenever anything is added or deleted.

2
You mean QAbstractListModel?Frank Osterfeld
@FrankOsterfeld, yes, I do19172281

2 Answers

0
votes

This may be usefull if you want to process raw QObject instance in QML script. You can append properties to Element class and modify them from qml.

class Element : public QObject {
  Q_OBJECT
  private:
    QString type;
    QLinkedList<Element*> child;
  public:
    explicit Element(QString type, QLinkedList<Element*> child);
    virtual ~Element();
  public:
    QLinkedList<Element*> getChild() const;
    QString getType() const;
  public:
    static void printTree(Element* root);
};

enter image description here

0
votes

this is so simple you need to use NOTIFY define your properties like this :

Q_PROPERTY (QString name READ name WRITE setName NOTIFY nameChanged)

then you need to define each one like this :

public : QString name() const;

signals :
void nameChanged(QString name);

public slots:
void setName(const QString &name);

private QString _name;

and then you should define body in cpp like this :

QString className::name() const{
   return _name;
}
void className::setName(const QString &name){
    if(name==_name) return;
    _name = name;
    Q_EMIT nameChanged(_name);

}

after registering it to QML with qmlRegisterType<ClassName>("com.className",1,0,"className");

simply set name it will notify if it changes for example in a textfield set text to that name property