Sunny31
8th December 2010, 15:52
I tried to connect a QML-Signal with a C++-Slot, but it didn't work.
It didn't call the C++-Slot, but the connection was successful (return value from QObject::connect).
Here is the code:
// main.cpp
#include <QtDeclarative>
#include "MyClass.hpp"
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QDeclarativeView view;
MyClass myClass;
QObject *object = view.rootContext();
QObject::connect(object, SIGNAL(mySignal()), &myClass, SLOT(cppSlot()));
view.setSource(QUrl::fromLocalFile("MyItem.qml"));
view.show();
return app.exec();
}
// myclass.hpp
#ifndef MYCLASS_HPP
#define MYCLASS_HPP
#include <QObject>
#include <QDebug>
class MyClass : public QObject
{
Q_OBJECT
public slots:
void cppSlot() {
qDebug() << "Called the C++ slot with";
}
};
#endif // MYCLASS_HPP
// MyItem.qml
import QtQuick 1.0
Item {
width: 100; height: 100
Rectangle {
anchors.fill: parent
color: "black"
}
signal mySignal()
MouseArea {
anchors.fill: parent
onClicked: {
mySignal()
}
}
}
I would be very thankful, if somebody could help me!
thanks
Added after 1 2 minutes:
I solved it:
I called the functions in the wrong order, main.cpp should look like this:
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QDeclarativeView view;
view.setSource(QUrl::fromLocalFile("MyItem.qml"));
MyClass myClass;
QObject *object = view.rootObject();
QObject::connect(object, SIGNAL(mySignal()), &myClass, SLOT(cppSlot()));
view.show();
return app.exec();
}
It didn't call the C++-Slot, but the connection was successful (return value from QObject::connect).
Here is the code:
// main.cpp
#include <QtDeclarative>
#include "MyClass.hpp"
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QDeclarativeView view;
MyClass myClass;
QObject *object = view.rootContext();
QObject::connect(object, SIGNAL(mySignal()), &myClass, SLOT(cppSlot()));
view.setSource(QUrl::fromLocalFile("MyItem.qml"));
view.show();
return app.exec();
}
// myclass.hpp
#ifndef MYCLASS_HPP
#define MYCLASS_HPP
#include <QObject>
#include <QDebug>
class MyClass : public QObject
{
Q_OBJECT
public slots:
void cppSlot() {
qDebug() << "Called the C++ slot with";
}
};
#endif // MYCLASS_HPP
// MyItem.qml
import QtQuick 1.0
Item {
width: 100; height: 100
Rectangle {
anchors.fill: parent
color: "black"
}
signal mySignal()
MouseArea {
anchors.fill: parent
onClicked: {
mySignal()
}
}
}
I would be very thankful, if somebody could help me!
thanks
Added after 1 2 minutes:
I solved it:
I called the functions in the wrong order, main.cpp should look like this:
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QDeclarativeView view;
view.setSource(QUrl::fromLocalFile("MyItem.qml"));
MyClass myClass;
QObject *object = view.rootObject();
QObject::connect(object, SIGNAL(mySignal()), &myClass, SLOT(cppSlot()));
view.show();
return app.exec();
}