gpt4 book ai didi

c++ - Qt C++信号转Qml

转载 作者:行者123 更新时间:2023-12-01 14:51:37 25 4
gpt4 key购买 nike

我正在尝试在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没有收到信号?

最佳答案

您有两个QmlCppApi创建的实例。一个在main.cpp中,您调用api,另一个在QML中,QML是未命名的HandleQmlCppApi对象。您只需要其中之一。要从api捕获信号,您需要一个Connections对象,如下所示:

Connections {
target: api

onTestStringSended: console.log("recieved")
}

关于c++ - Qt C++信号转Qml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63194332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com