[英]Qt C++ Signal to Qml
I am attempting to catch a C++ Qt Signal in Qml.我试图在 Qml 中捕获 C++ Qt 信号。 I am able to send a signal, and catching a Qml Signal in Qt is working too;
我能够发送信号,并且在 Qt 中捕获 Qml 信号也在工作; however, I cannot catch a Qt signal in Qml.
但是,我无法在 Qml 中捕捉到 Qt 信号。
Which QObject::connect do i need?我需要哪个 QObject::connect?
minimal main.cpp:最小的 main.cpp:
#include <QtGui/QGuiApplication>
#include <QtQml/QQmlApplicationEngine>
#include <QQmlContext>
#include <QQuickWindow>
#include "qmlcppapi.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
qmlRegisterType<QmlCppApi>("com.handleQmlCppApi",1,0,"HandleQmlCppApi");
QQmlApplicationEngine engine;
const QUrl url(QStringLiteral("qrc:/qml/qmlfile.qml"));
QmlCppApi api;
engine.rootContext()->setContextProperty("api", &api);
engine.load(url);
QObject::connect(&api, &QmlCppApi::testStringSended,
&api, &QmlCppApi::printTestString);
return app.exec();
}
minimal gmlcppapi.hpp: Slot is only for showing if the signal is emitted最小 gmlcppapi.hpp:插槽仅用于显示是否发出信号
#ifndef QMLCPPAPI_H
#define QMLCPPAPI_H
#include <QObject>
#include <QDebug>
class QmlCppApi : public QObject
{
Q_OBJECT
public:
Q_INVOKABLE void postTestString(QString TestString) {
qDebug() << "cpp: recieved";
emit testStringSended(TestString);
}
public slots:
void printTestString(QString TestString) {
qDebug() << "cpp: sended";
}
signals:
void testStringSended(QString TestString);
};
#endif // QMLCPPAPI_H
minimal qmlfile.qml: The ToggleButton should execute the cpp function testStringSended.最小 qmlfile.qml:ToggleButton 应该执行 cpp function testStringSended。 And the printTestString is firering a emit which should triggers the onTestStringSended
并且 printTestString 正在触发一个应该触发 onTestStringSended 的发射
import QtQuick 2.2
import QtQuick.Window 2.1
import QtQuick.Controls 1.4
import QtQuick.Controls.Styles 1.4
import QtQuick.Extras 1.4
import com.handleQmlCppApi 1.0
Window {
visible: true
ToggleButton {
onClicked: {
console.log("send")
api.postTestString("TestString")
}
}
HandleQmlCppApi {
onTestStringSended: console.log("recieved")
}
}
output: output:
qml: send
cpp: recieved
cpp: sended
Why is my Qml not receiving the signal?为什么我的 Qml 收不到信号?
You have two instances of QmlCppApi that you created.您有两个创建的 QmlCppApi 实例。 One is in main.cpp, that you call
api
, and the other is in QML which is the unnamed HandleQmlCppApi object.一个在 main.cpp 中,你称之为
api
,另一个在 QML 中,它是未命名的 HandleQmlCppApi object。 You only need one of them.你只需要其中之一。 To catch a signal from
api
you need a Connections
object, like this:要捕获来自
api
的信号,您需要一个Connections
object,如下所示:
Connections {
target: api
onTestStringSended: console.log("recieved")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.