Search code examples
c++qtqmlqt-quickmoc

C++ using signal slots for QML


I have a small class that is not working properly, and I can't get what is wrong with it. The compiler gives the message:

main.cpp: error: undefined reference to 'CDetails::CDetails()'

This is the snapshot from the code:

//main.cpp
#include <QtGui/QGuiApplication>
#include "qtquick2applicationviewer.h"
#include <QQmlContext>
#include <QDebug>

class CDetails : public QObject
{   Q_OBJECT
    public:
        CDetails() {}
        ~CDetails(void) {}


    public slots:
        void cppSlot(const QString &msg)
        {    qDebug() << "Called the C++ slot with message:" << msg;
        }
};

int main(int argc, char *argv[])
{   QGuiApplication app(argc, argv);
    QtQuick2ApplicationViewer viewer;
    viewer.setMainQmlFile(QStringLiteral("qml/testqml/main.qml"));
    viewer.showExpanded();

    CDetails *test = new CDetails();
    QObject::connect((QObject*)viewer.rootObject(),
                 SIGNAL(qmlSignal(QString)),test,
                 SLOT(cppSlot(QString)));
    return app.exec();
}

And in main.qml:

import QtQuick 2.0
Rectangle {
    id: guide
    width: 360
    height: 360
    signal qmlSignal(string msg)
    Text {
        text: qsTr("Hello World")
        anchors.centerIn: parent
    }
    property double scaleFactor: 1.0
    property string iconUrl: "image.png"
    MouseArea {
        anchors.fill: parent
        onClicked: {
            guide.qmlSignal("Hello from QML")
        }
    }
}

Update: Thanks for the suggestion on constructor. Now the error is:

error: undefined reference to 'vtable for CDetails'

What is missed here? All suggestions are welcome.


Solution

  • You're missing implementations of your constructor and destructor. Quick fix:

    class CDetails : public QObject
    {   Q_OBJECT
    public:
      CDetails() {}
      ~CDetails(void) {}
       ...
    };