Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/132.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ QT-连接Qml按钮单击到Cpp构造函数_C++_Qt_Qml_Signals Slots - Fatal编程技术网

C++ QT-连接Qml按钮单击到Cpp构造函数

C++ QT-连接Qml按钮单击到Cpp构造函数,c++,qt,qml,signals-slots,C++,Qt,Qml,Signals Slots,这是我的代码(它没有编译,在main.cpp中标记connect时说:“前面应该有主表达式”,“token”) main.cpp QObject *myButton = engine.rootObjects().first() -> findChild<QObject*>("btn"); QObject::connect(myButton, SIGNAL(clicked()), MyClass, SLOT(MyClass())); MyClass myClass; engin

这是我的代码(它没有编译,在main.cpp中标记connect时说:“前面应该有主表达式”,“token”)

main.cpp

QObject *myButton = engine.rootObjects().first() -> findChild<QObject*>("btn");
QObject::connect(myButton, SIGNAL(clicked()), MyClass, SLOT(MyClass()));
MyClass myClass;
engine.rootContext() -> setContextProperty("_btn", &myClass);
我希望每次单击按钮时都实例化cpp类MyClass

我以前做过一件不同的事情,但它在应用程序运行时实例化MyClass,而不是在单击按钮时。此外,我不能调用构造函数,只能调用Q_可调用的公共方法

main.cpp

QObject *myButton = engine.rootObjects().first() -> findChild<QObject*>("btn");
QObject::connect(myButton, SIGNAL(clicked()), MyClass, SLOT(MyClass()));
MyClass myClass;
engine.rootContext() -> setContextProperty("_btn", &myClass);
main.qml

ApplicationWindow {
    id: appWindow
    visible: true
    width: 850; height: 500
Button
{
objectName: btn
anchors.centerIn: parent
}
}
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的类的实例(不是您在代码段中所述的定义),所以您需要类的实例来使用信号槽机制。这就是编译失败的原因


要完成任务,您必须创建一些“代理”类并连接到is插槽,您将在其中动态创建
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的类的实例(不是您在代码段中所述的定义),所以您需要类的实例来使用信号槽机制。这就是编译失败的原因

要完成任务,您必须创建一些“代理”类并连接到is插槽,在这里您将动态创建
MyClass