[英]Qt create object in c++ and expose to QML
我正在嘗試開發游戲,但不僅與游戲有關,而且與任何東西有關。 我的問題是:如何在c ++上創建/刪除/管理對象,並且它們在qml中出現/消失/更改?
我知道很多用戶會告訴我閱讀
http://doc.qt.io/qt-4.8/qtbinding.html
http://doc.qt.io/qt-5/qtqml-cppintegration-contextproperties.html
http://doc.qt.io/qt-5/qtqml-cppintegration-interactqmlfromcpp.html
http://doc.qt.io/qt-5/qtqml-cppintegration-exposecppattributes.html
等等...
我已經看完了。 我知道如何以某種方式使用它,例如更改數字的示例,它是一個屬性,並且它在QML中公開,因此它會自動更改,但這不是我的問題。
讓我們以一些簡單的代碼為例
class Unit {
int posX, posY;
int energy;
void move()...
void create()...
void kill()
}
然后,我們將在主要子句和所有必要子句中使用c ++實現所有邏輯。
Game.cpp
class Game {
QList<Unit> listUnits;
moveUnits() {
for (int i = 0; i < units.size(); i++){
Unit unit;
unit.move();
}
createNewUnit(){
Unit unit = new Unit();
listUnits.append(unit);
}
}
On the other side will have Unit.qml
Item{
property int posX;
property int posY;
Animation on X {...}
....
}
這基本上是處理與Unit相關的UI,但我重復一遍,所有邏輯將再次在c ++中完成。
在前面提到的示例中,我想在創建新單元時將其直接顯示在QML中。
怎么做? 我真的確定有可能做到,而且我確定很簡單,我只是沒有發現。 我不需要代碼,僅是提示,也無需參考或教程。
如果解決方案確實在我之前寫過的一封電子郵件中,請讓我詳細解釋一下,因為我仍然沒有發現。
非常感謝!
這是如何將C ++連接到QML
public:
上方具有Q_OBJECT
宏public:
在某些公共方法之前添加Q_INVOKABLE
宏,以便可以從QML調用它們。 例如Q_INVOKABLE int doStuff(int myParam);
在主文件中,注冊該類,以便QML可以找到它: qmlRegisterType<Foo>("MyFoo", 1, 0, "Foo");
import MyFoo 1.0
C ++類,然后import MyFoo 1.0
(請注意,它是1.0,因為在qmlRegisterType中,我傳遞了參數1和0) 現在,您可以將C ++類添加到QML文件中。 Foo { id: foo}
並可以從QML中的其他地方調用您的方法,例如
函數qmlDoSomething(val){var newInt = foo.doStuff(val)}
如果要動態創建QML組件,可以這樣做:
function addComponent(){
var comp = Qt.createComponent("ComponentFile.qml")
var sprite = comp.createObject(myParent) //myParent should be whatever you want to add the component to
}
如果希望QML響應C ++消息,請向C ++添加信號
signals:
void makeComponent(QString message);
然后在QML窗口小部件中,您可以為該信號何時被調用
Foo{
id: foo
onMakeComponent: {
console.log(message);
addComponent()
}
}
如果您不熟悉信號的工作原理,那很簡單。 在C ++方法中,您只需要使用關鍵字發射,然后像調用它一樣調用它
void myFunc(){
//Do some stuff
emit(makeComponent(someString));
}
如果您希望新創建的QML元素將數據發送回C ++
function addComponent(componentName){
var comp = Qt.createComponent("ComponentFile.qml")
var sprite = comp.createObject(myParent)
sprite.name = componentName
sprite.mySignal.connect(foo.modifyComponent)
}
//In ComponentFile.qml
signal mySignal(string val)
function sendSignal(){
mySignal(name)
}
總而言之,我已經解釋了如何:
這應該是在QML和C ++之間傳遞數據所需的一切
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.