提问者:小点点

Qt C++信号到Qml


请帮帮我。

我无法捕捉QML中的Qt C++信号。 发送是可能的。 在Qt C++中捕获Qml信号也是可能的。

没有CompileErrors。

我需要哪个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"));
    engine.load(url);
    QmlCppApi api;
    engine.rootContext()->setContextProperty("api", &api);
    QObject::connect(&api, &QmlCppApi::testStringSended, &api, &QmlCppApi::printTestString);
    return app.exec();
}

minimal GMLCPPAPI.hpp:Slot仅用于在发射器被激发时显示

#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:ToggleButton应该执行cpp函数TestStringSended。 并且printTestString正在触发一个应该触发onTestStringSended的emit

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

共1个答案

匿名用户

您创建了两个QmlCppApi实例。 一个在main.cpp中,您将其称为API,另一个在QML中,它是未命名的HandleQmlCppApi对象。 你只需要其中一个。 要从API捕获信号,您需要一个Connections对象,如下所示:

Connections {
    target: api

    onTestStringSended: console.log("recieved")
}

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(qt|c++|信号|qml)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?