Reputation: 645
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();
}
}
}
Upvotes: 1
Views: 1866
Reputation: 717
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");
Upvotes: 2