【发布时间】:2020-07-31 15:00:20
【问题描述】:
我正在尝试在 Qml 中捕获 C++ Qt 信号。我能够发送信号,并且在 Qt 中捕获 Qml 信号也可以;但是,我无法在 Qml 中捕获 Qt 信号。
我需要哪个 QObject::connect?
最小的 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();
}
最小 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
最小的 qmlfile.qml: ToggleButton 应该执行 cpp 函数 testStringSended。并且 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")
}
}
输出:
qml: send
cpp: recieved
cpp: sended
为什么我的 Qml 没有收到信号?
【问题讨论】: