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.
}
}