QT - 连接Qml按钮点击Cpp构造函数

QT - Connect Qml button Click to Cpp Constructor

这是我的代码(无法编译,在 main.cpp 中标记连接时说:"expected primary-expression before ‘,’ token")

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 class MyClass

我之前做了不同的事情,但它有在应用程序运行时实例化 MyClass 的问题,而不是在单击按钮时。此外,我无法调用构造函数,只能调用 Q_INVOKABLE public 方法。

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

请看一下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 是基于 QObject class 的实例(不是您在代码段中所述的定义),因此您需要一个实例 class 才能使用信号槽机制。这就是你编译失败的原因。

要完成您的任务,您必须创建一些 "proxy" class 并连接到插槽,您将在其中动态创建 MyClass