Qml call c++ function with CMake
Unsolved
QML and Qt Quick
-
If i use qmake, the following way works fine: If i want call a function from the class Test2, i do the following:
test2.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(); }
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 REQUIRED) 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)
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()'.
-
When you don't add test2.cpp to the sources to compile the linker also cant find the class...
-
If i have a normal c++ project, i didn't add the source file, too.
But if i addset( project_sources main.cpp test2.cpp )
it doesn't work, either.
-
Thank you very much. I don't added the source file to executable. Now all works fine.