Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate C++ component in QML - WITH Parameterized Constructor

Tags:

c++

qt-quick

qml

In hypothetical example, I have a C++ component -

class Board : public QObject
{
    Q_OBJECT
public:
    //Q_PROPERTYs go here
    explicit Board(int rows, int columns)
    {
        matrix = std::vector<int>(rows, std::vector<int>(columns, 0));
    }

    ~Board()
    {
        matrix.clear();
    }

    Q_INVOKABLE void checkAndUpdateAdjecentCells(int row, int column);
    //setters and getters here.

signals:
    void matrixUpdated();

private:
    Board(QObject *parent) = default; //i intend to do this.
    Board(Board& b) = delete;
    int nRows_, nCols_;
    std::vector<std::vector> matrix;
};

registered in main() like -

qmlRegisterType<Board>("SameGameBackend", 1, 0, "BubbleBoard");

Question

How do I instantiate this in QML such that the parameterized constructor is invoked ?

Expected QML code -

BubbleBoard{
    id: bboard
    rows: 10
    columns: 10
}

We can extend this question to include initializer list. Had nRows_ and nCols_ been const int, constructor would have been

explicit Board(int rows, int columns):nRows_(rows), nCols_(columns){}

Is it possible to instantiate such components from inside QML ?

like image 694
essbeev Avatar asked Apr 21 '16 08:04

essbeev


2 Answers

May be a solution would be to register an uncreatable type and register a factory class which creates the object with parameters.

For instance I use a model factory to create sql models from C++ with filter parameters.

ModelFactory {
 id: modelFactory
}

ListView {
  model: modelFactory.createModel(filterparam1, filterparam2)
}
like image 87
jonjonas68 Avatar answered Nov 08 '22 09:11

jonjonas68


Q_PROPERTY is the only way to send your parameters using QML property

like image 36
DenimPowell Avatar answered Nov 08 '22 08:11

DenimPowell