-2

In my C++ program, I want to be able to load a file at runtime which contains the data for several employees (first name, last name, DOB). This file should be interpreted and Employee objects created for each employee, and stored in some sort of list (maybe QList?).

On the QML side of things, I have an 'employee.qml' file which is essentially a rectangle with a few text fields in it.

As my Employee objects are created, I also want to create instances of my 'employee.qml' component, and bind each one to its respective Employee object, such that the text field reflects the data in the C++ object.

Effectively, for each Employee object, a new component should be placed on the screen, and be bound to the correct object. It should also be able to call public slots methods defined in the class.

Is this even possible with Qt and QML?

EDIT:

One possible idea might be to use QQmlComponent::create() in C++, set the id to the name of the C++ object using SetProperty(), and use setContextProperty to make the object available to QML.

19172281
  • 237
  • 2
  • 10
  • Possible duplicate of [how to create components dynamically in qml](https://stackoverflow.com/questions/48166044/how-to-create-components-dynamically-in-qml) – Mohammad Kanan Aug 24 '19 at 20:03
  • What did you try and didnt work ? https://doc.qt.io/qt-5/qtqml-javascript-dynamicobjectcreation.html – Mohammad Kanan Aug 24 '19 at 20:03

1 Answers1

0

A simple way to achieve this is to subclass QAbstractListModel to create your own EmployesListModel , parse your csv file etc.. and expose it to QML, where you can use a Repeater. The final QML Code should look like:

EmployeesListModel
{
    id: employeesListModel
    source: "/path/to/employees.csv"
}

Repeater
{
    model: employeesListModel
    delegate: Text { text: "Hi, my name is %1 and i am %2 years old".arg(employeeName).arg(employeeAge) }
}

Dinesh
  • 449
  • 2
  • 5
  • But how would I bind it to the C++ objects stored in my Model? – 19172281 Aug 25 '19 at 14:44
  • Each instance of the delegate is already bound to the corresponding row/object in the model. I have updated the code sample to show the delegate using roles like `employeeName`, `employeeAge` - which should be exposed by the model. Alternatively You can just expose a whole QObject as a single role and directly interact with it's properties in QML – Dinesh Aug 25 '19 at 17:18
  • @Thanks, I'll give it a go. In terms of positioning the instances of 'employee.qml', if I store x,y coordinates in my Employee objects, how can I use them on the QML side to place the object where specified? – 19172281 Aug 25 '19 at 17:46