[英]How to instantiate C++ component in QML - WITH Parameterized Constructor
在假設的例子中,我有一個C ++組件 -
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;
};
在main()
注冊喜歡 -
qmlRegisterType<Board>("SameGameBackend", 1, 0, "BubbleBoard");
題
如何在QML中實例化這樣,以便調用參數化構造函數?
預期的QML代碼 -
BubbleBoard{
id: bboard
rows: 10
columns: 10
}
我們可以將此問題擴展到包含初始化列表。 如果nRows_
和nCols_
是const int
,那么構造函數就是
explicit Board(int rows, int columns):nRows_(rows), nCols_(columns){}
是否可以從QML內部實例化這些組件?
Q_PROPERTY是使用QML屬性發送參數的唯一方法
可能是一個解決方案是注冊一個不可創建的類型並注冊一個工廠類,該工廠類用參數創建對象。
例如,我使用模型工廠從C ++創建帶有過濾器參數的sql模型。
ModelFactory {
id: modelFactory
}
ListView {
model: modelFactory.createModel(filterparam1, filterparam2)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.