PDA

View Full Version : [SOLVED] qml signal with c++ slot



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();
}

gaolinjie
22nd February 2011, 10:37
I had the same problem with you, so thanks for your solved post.

JandunCN
22nd January 2014, 04:16
I now encounters the same problem, thanks for you tip.

Added after 1 56 minutes:

I am confused now.I did it in Qt 5.2 in the way the code below shows. And the result was that connection( c++ signal to QML function ) worked well,but connection(QML signal to C++ slot) didn't work.Did I ignore something important,I only knew that there were some differences between Qt4's way achieving this and Qt5's.Any tip is appreciated,thanks in advance.Sorry for my poor English.

// main.cpp in Qt 5.2
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);

QtQuick2ApplicationViewer viewer;
viewer.setMainQmlFile(QStringLiteral("qml/TestInvokeMethod/main.qml"));
Test* test = new Test() ;
QQmlEngine engine;
QQmlComponent component(&engine, "qml/TestInvokeMethod/main.qml");
QObject *object = component.create();
QObject::connect( object, SIGNAL( toCode( /*QString*/ ) ), test, SLOT( emittedByQml( /*QString*/ ) ) ); // didn't work.
QObject::connect( test, SIGNAL( toQml( QVariant ) ), object, SLOT( emittedByCode( QVariant ) ) ) ;
test->toQml( "toQml" ) ;
delete object ;
viewer.showExpanded();

return app.exec();
}

anda_skoa
22nd January 2014, 08:47
SIGNAL and SLOT macros only contain function names and argument types.
/*QString*/ is neither, it is a comment.

Cheers,
_