0

I have a vector in c++, where each element is a object of the same class. The properties of these objects are strings and integers.
Now I want to create rectangles in QML depending on how many elements are in the vector (1 rectangle per element) and the rectangle's features (x and y position for example) depend on the values of properties of the objects in the vector (the integer properties). My question is: how do I import this data from c++ into QML? And how do I use the x/y Positions to create rectangles on these values?
This is a example of the cpp file:

#include <iostream>
#include <vector>
#include <string>

class myClass{
    public:
        int xPosition;
        int yPosition;
        std::string color;

        myClass(int xPosition_, int yPosition_, std::string color_){
            xPosition = xPosition_;
            yPosition = yPosition_;
            color = color_;
        }
};

int createVec(){
    myClass objectOne(100, 100, "red");
    myClass objectTwo(200, 200, "blue");
    myClass objectThree(300, 300, "green");
    myClass objectFour(400, 400, "black");


    std::vector<myClass> vec;
    vec.push_back(objectOne);
    vec.push_back(objectTwo);
    vec.push_back(objectThree);
    vec.push_back(objectFour);

    for (int i = 0; i < vec.size(); i++){
        std::cout << vec[i].xPosition << " " << vec[i].yPosition << " " <<vec[i].color << std::endl;
    }
}

Edit: I tried to solve my problem mainly by doing something similar to this post. However I'm running into multiple different problems, since I'm very new to QML, qt and c++. First of all I don't know how to convert my class into a Q_OBJECT, secondly I don't know what eatyourgreens meant with:

In the QML code, the properties of Thing can be accessed through the model as model.modelData.size and model.modelData.name.

Vipr0
  • 59
  • 7
  • This issue is widely covered in the Qt documentation as well as at SO. Did you try to get an answer using that before asking? [Integrating QML and C++](https://doc.qt.io/qt-5/qtqml-cppintegration-topic.html), [Interacting with QML Objects from C++](https://doc.qt.io/qt-5/qtqml-cppintegration-interactqmlfromcpp.html) – folibis Jun 08 '20 at 17:31
  • Yes I tried fixing my problems for days by reading the documentation and trying several things, but I just can't get it to work unfortunately. That's why I'm asking for help here now. – Vipr0 Jun 08 '20 at 21:15

1 Answers1

0

You might use

YourClass *yourClass = new YourClass();
    qmlView->rootContext()->setContextProperty("myClass", yourClass);
note: where your system calling the qml (it might be in main.cpp)

inside qml file. you may get the property or method that has return value like this

myClass.getFloorProperty();