[英]Connect C++ signal to QML slot
I'm trying to connect a C++ signal with a QML slot.我正在尝试将 C++ 信号与 QML 插槽连接起来。
The C++ signal is called userRegistered()
and the QML slot is called userRegisteredQML()
. C++ 信号称为userRegistered()
,QML 槽称为userRegisteredQML()
。
In the C++ file, I have the following:在 C++ 文件中,我有以下内容:
QQuickView view(QUrl::fromLocalFile("interface.qml"));
QObject *topLevel = view.rootContext();
connect(myClass, SIGNAL(userRegistered()), topLevel, SLOT(userRegisteredQML()));
And in the interface.qml
, I have the slot userRegisteredQML
:在interface.qml
中,我有插槽userRegisteredQML
:
function userRegisteredQML(){
console.log("this is a test!");
}
The problem is that it does not show "this a test!".问题是它没有显示“这是一个测试!”。 Therefore, I wanted to ask you if this is the proper way to connect a C++ signal to a QML slot.因此,我想问你这是否是将 C++ 信号连接到 QML 插槽的正确方法。
QML js functions are not slots. QML js 函数不是插槽。
You should just create the signal in C++ and in QML you handle it with on.您应该只在 C++ 中创建信号,然后在 QML 中处理它。
This is Also where exactly that signal exists.这也是该信号确切存在的地方。
If it is a QML_ELEMENT
you would handle it inside the component instantiation in QML.如果它是QML_ELEMENT
,您将在 QML 的组件实例化中处理它。
SomeTypeFromC++{
onUserRegistered: {do_somthing()}
}
If it is in an engine rootContextProperty
You can use Connections QML type:如果它在引擎rootContextProperty
中,则可以使用Connections QML 类型:
Connections {
target: appCore // The name of the context property
onUserRegistered: {do_somthing()}
}
Expose your object to QML in C++:在 C++ 中将您的对象暴露给 QML:
topLevel->setContextProperty("MyClass", myClass);
In QML, you can use Connections:在 QML 中,您可以使用连接:
Connections {
target: MyClass
userRegistered: {
// do something with it here
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.