简体   繁体   中英

C++ and QML: Connect QML Signal to C++ Slot

I cannot get the signal connection in the following code to work. I specifically want to do this via connecting the signal to a cpp slot and not setting the context. I suppose the problem is that

 item->findChild<QObject*>("signalItem");

does not find the right object? Here the relevant code files:

main.cpp:

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "include/myclass.h"

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QLatin1String("qrc:/main.qml")));
    QObject * item = engine.rootObjects().value(0);
    QObject * myObject= item->findChild<QObject*>("signalItem");
    MyClass myClass;
    QObject::connect(item, SIGNAL(testSignal()),&myClass,SLOT(cppSlot()));

    return app.exec();
}

main.qml:

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.0

ApplicationWindow {
    visible: true
    width: 800
    height: 460

    Page1 {
        id: page1
        visible: true
    }
}

Page1.qml:

import QtQuick 2.7
import QtQuick.Window 2.2

Item {
    width: 800
    height: 460
    id: signalItem
    objectName: "signalItem"
    signal testSignal()

    CustomButton {
        id: cppSignalButton
        x: 14
        y: 55
        buttonText: "Test CPP Signal"
        onButtonClicked: {
            signalItem.testSignal();
        }
     }
}

Because you are connecting item (main.qml) instead of myObject

If you do so, it will work:

QObject::connect(myObject, SIGNAL(testSignal()),&myClass,SLOT(cppSlot()));

Actually you should also add checking if returned values from that functions aren't null:

QObject * item = engine.rootObjects().value(0);
QObject * myObject= item->findChild<QObject*>("signalItem");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM