Facing issue with integration of C++ with QML
Solved
General and Desktop
-
I have started learning about QML and I started with a basic application
I am facing this issue "Cannot assign to non-existent default property"
backtest.h
#ifndef BACKTEST_H #define BACKTEST_H #include <QObject> class BackTest:public QObject { Q_OBJECT Q_PROPERTY(int iVal READ getIVal WRITE setIVal RESET resetIVal NOTIFY iValChanged FINAL) private: int iVal; public: BackTest(); int getIVal() const; void setIVal(int newIVal); void resetIVal(); signals: void iValChanged(); }; #endif // BACKTEST_H
backTest.cpp
#include "backtest.h" BackTest::BackTest() {} int BackTest::getIVal() const { return iVal; } void BackTest::setIVal(int newIVal) { if (iVal == newIVal) return; iVal = newIVal; Q_EMIT iValChanged(); } void BackTest::resetIVal() { setIVal({}); // TODO: Adapt to use your actual default value }
main.cpp
#include <QGuiApplication> #include <QQmlApplicationEngine> #include <backtest.h> int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); QQmlApplicationEngine engine; qmlRegisterType<BackTest>("MyCppClassModule", 1, 0, "BackTest"); const QUrl url(u"qrc:/untitled2/Main.qml"_qs); QObject::connect( &engine, &QQmlApplicationEngine::objectCreationFailed, &app, []() { QCoreApplication::exit(-1); }, Qt::QueuedConnection); engine.load(url); return app.exec(); }
main.qml
import QtQuick import QtQuick.Controls import MyCppClassModule 1.0 Window { width: 640 height: 480 visible: true title: qsTr("Hello World") BackTest { id: myCppClassInstance Component.onCompleted: { myCppClassInstance.iVal = 42; } Text { text: "Property value: " + myCppClassInstance.getIVal } } }
Kindly help me with what I am missing
-
@ManiRon28 I think this might be because you are trying to add
Text
(a visual element) as a child toBackTest
which is a pure QObject, no visuals.Try:
BackTest { id: myCppClassInstance Component.onCompleted: { iVal = 42; } } Text { text: "Property value: " + myCppClassInstance.getIVal }
-