0

If i use qmake, the following way works fine: If i want call a function from the class Test2, i do the following test.h :

#ifndef TEST2_H
#define TEST2_H

#include <QObject>

class Test2: public QObject
{
    Q_OBJECT
public:
    Test2();
public slots:
    int testit();
};

#endif // TEST2_H

test2.cpp:

Test2::Test2()
{

}

int Test2::testit()
{
    return 6;
}

main.cpp:

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "test2.h"

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;

    QQmlContext* context= engine.rootContext();
    Test2 test2instance;
    context->setContextProperty("test", &test2instance);


    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

So i can call test.testit() in qml. But if i do this with CMake it doesn't work. The error message is: error: undefined reference to `Test2::Test2()'

My CMakeList:

cmake_minimum_required(VERSION 3.1)

project(QMLCmake LANGUAGES CXX)

set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

find_package(Qt5 COMPONENTS Core Quick)

add_executable(${PROJECT_NAME} "main.cpp" "qml.qrc")
target_compile_definitions(${PROJECT_NAME} PRIVATE $<$<OR:$<CONFIG:Debug>,$<CONFIG:RelWithDebInfo>>:QT_QML_DEBUG>)
target_link_libraries(${PROJECT_NAME} PRIVATE Qt5::Core Qt5::Quick)
Orion
  • 231
  • 1
  • 2
  • 8

0 Answers0