[英]C++ Signal is not received in QML slot
I have a C++ class that emits a signal.我有一个发出信号的 C++ 类。 I want that signal to be delivered to QML.
我希望将该信号传递给 QML。 I set the object as a context property of qml application engine root context.
我将该对象设置为 qml 应用程序引擎根上下文的上下文属性。
My C++ class我的 C++ 课
// Sample.h
class Sample : public QObject
{
Q_OBJECT
public:
explicit Sample(QObject *parent = nullptr);
public slots:
void emitSomething();
signals:
void emitted();
public slots:
};
And the implementation和实施
// Sample.cpp
Sample::Sample(QObject *parent) : QObject(parent)
{
}
void Sample::emitSomething()
{
emit emitted();
}
My main implementation.我的主要实现。 This is very similar to the code provided by qt creator.
这与qt creator 提供的代码非常相似。
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
Sample sample;
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("obj", &sample);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
QTimer::singleShot(1000, &sample, &Sample::emitSomething);
return app.exec();
}
The qml implementation is qml 实现是
import QtQuick 2.9
import QtQuick.Window 2.2
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Connections {
target: obj
onEmitted: function() {
console.log("received")
}
}
}
When I run the code, emitSomething()
slot is called, but I don't see emitted()
signal in qml.当我运行代码时,
emitSomething()
槽,但是我在emitSomething()
没有看到emitted()
信号。
I didn't have version 5.9, but I tried it with 5.10.1.我没有 5.9 版,但我用 5.10.1 试过了。 In that case, the text did not get printed to the console.
在这种情况下,文本不会打印到控制台。 I fixed it by changing the syntax on the signal handler.
我通过更改信号处理程序的语法来修复它。 (Just remove
function()
.) (只需删除
function()
。)
Connections {
target: obj
onEmitted: {
console.log("received")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.