C++ class wouldn't build in bare bone QML application



  • I have a simple bare bone QML application and I just want to add a c++ class and use it from QML but I get error and it wouldn't even build. Here is the code.

    @#include <QGuiApplication>
    #include <QQmlApplicationEngine>

    #include "mymodel.h"

    int main(int argc, char *argv[])
    {
    QGuiApplication app(argc, argv);

    MyModel model;
    
    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    

    // engine.rootContext()->setContextProperty("_MyModel", &model);

    return app.exec&#40;&#41;;
    

    }@

    And the class MyModel is:

    @#ifndef MYMODEL_H
    #define MYMODEL_H

    #include <QObject>

    class MyModel : public QObject
    {
    Q_OBJECT
    public:
    explicit MyModel(QObject *parent = 0);

    signals:

    public slots:

    };

    #endif // MYMODEL_H@

    the .cpp file of the class

    @#include "mymodel.h"

    MyModel::MyModel(QObject *parent) :
    QObject(parent)
    {
    }
    @

    When I build, I get the following error:

    @
    main.obj:-1: error: LNK2019: unresolved external symbol "public: __thiscall MyModel::MyModel(class QObject *)" (??0MyModel@@QAE@PAVQObject@@@Z) referenced in function _main
    debug\QMLCalc1.exe:-1: error: LNK1120: 1 unresolved externals
    @

    What is possibly wrong? I can't even get to the setContextProperty() call yet.



  • Have included mymodel.cpp into the project?


  • Moderators

    Also, unrelated to above error, use setContextProperty before loading the QML or else there would be some Reference Errors.



  • I had to 'Run QMake' from build menu which fixed it and project now builds fine without making any other change but I still don't uderstand why do I have to do that! It is a simple new project and I just added a class. Could anyone tell me what does QMake do? Can I add this as a step to build process? Thanks.



  • It generates the makes files again to compile your sources. You have added new class files to your project. So pro file got updated. I have seen some times it does not generate make file on its own after adding new class files. I have seen this more with when I'm using the qmake/qt creator with VC++. In general it is good practice to re-run the qmake once the pro-file is updated.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.