[英]Fail To Connect Qml signal to C++ Slot
I have been trying to connect signal between Qml file and c++, but public slot in c++ doesn't seem to receive the signal. 我一直试图在Qml文件和c ++之间连接信号,但是c ++中的公共插槽似乎没有收到信号。 What might be wrong with my program?
我的程序可能出什么问题了?
main.qml main.qml
Item{
id:item
signal qml_signal
Button{
onClicked: {
item.qml_signal();
}
}
}
main.cpp main.cpp中
QQuickView view(QUrl("qrc:/main.qml"));
QObject *item = view.rootObject();
Myclass myclass;
QObject::connect(item, SIGNAL(qml_signal()), &myclass,SLOT(cppSlot()));
myclass.h myclass.h
void cppSlot() ;
myclass.cpp myclass.cpp
void Myclass::cppSlot(){
qDebug() << "Called the C++ slot with message:";
}
When you want objects to interact between C++ and QML, you must do it on the QML side, since obtaining a QML object from C++ can cause you many problems, as in this case, the signal created in QML can not be handled in C++. 当您希望对象在C ++和QML之间交互时,必须在QML方面进行操作,因为从C ++获取QML对象可能会引起许多问题,因为在这种情况下,无法在C ++中处理在QML中创建的信号。
The solution is to export your object myclass
to QML and make the connection there: 解决方案是将您的对象
myclass
导出到QML并在那里建立连接:
main.cpp main.cpp中
#include "myclass.h"
#include <QGuiApplication>
#include <QQuickView>
#include <QQmlContext>
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQuickView view(QUrl("qrc:/main.qml"));
Myclass myclass;
view.rootContext()->setContextProperty("myclass", &myclass);
view.show();
return app.exec();
}
main.qml main.qml
import QtQuick 2.9
import QtQuick.Controls 1.4
Item{
id:item
signal qml_signal
Button{
onClicked: item.qml_signal()
}
onQml_signal: myclass.cppSlot()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.