2017-08-25 13 views
0

這裏是我的代碼(不能編譯,他說:「預期主表達式前‘’令牌」,同時標誌着在main.cpp中的連接)QT - 連接按鈕設爲Qml點擊CPP的構造

main.cpp中

QObject *myButton = engine.rootObjects().first() -> findChild<QObject*>("btn"); 
QObject::connect(myButton, SIGNAL(clicked()), MyClass, SLOT(MyClass())); 

main.qml

ApplicationWindow { 
    id: appWindow 
    visible: true 
    width: 850; height: 500 
Button 
{ 
objectName: btn 
anchors.centerIn: parent 
} 
} 

我希望cpp類MyClass在每次點擊按鈕時被實例化。

我以前做過不同的事情,但它有應用程序運行時實例化MyClass的問題,而不是點擊按鈕時。此外,我不能調用構造函數,而只能調用Q_INVOKABLE公共方法。

的main.cpp

MyClass myClass; 
engine.rootContext() -> setContextProperty("_btn", &myClass); 

main.qml

ApplicationWindow { 
    id: appWindow 
    visible: true 
    width: 850; height: 500 
Button 
{ 
objectName: btn 
anchors.centerIn: parent 
onClicked: _btn.myMethod() //where myMethod is a Q_INVOKABLE public method belonging to MyClass. 
} 
} 

回答

2

請看看QObject::connect定義

QMetaObject::Connection QObject::connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type = Qt::AutoConnection) 

參數1和3個是實例(N如您在代碼段中所述的定義),所以您需要您的類實例使用信號槽機制。這是編譯失敗的原因。

要完成您的任務,您必須創建一些「代理」類並連接到插槽,您將在其中動態創建MyClass