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 ?
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)
}
Q_PROPERTY is the only way to send your parameters using QML property
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With