How I change a property of a qml object from a cpp file?
-
Im using Qt Quick Controls 2 and Im a completly inexpert qith qml
and Im stocked here:
*.h file:#ifndef START_H #define START_H #include <QObject> #include <QString> class Image : public QObject { Q_OBJECT Q_PROPERTY(QString source READ source WRITE setSource NOTIFY sourceChanged) public: explicit Image(QObject *parent = nullptr); QString source(); void setSource(const QString &source); signals: void sourceChanged(); protected: QString m_source = "648115.jpg"; }; #endif // START_H
*.cpp file:
#include "start.h" Image::Image(QObject *parent) : QObject(parent) {} QString Image::source() { return m_source; } void Image::setSource(const QString &source) { if (source == m_source) return; m_source = source; emit sourceChanged(); }
*.qml file:
import PTrans.class.Imagen 1.0 Image { id: backg anchors.fill: parent fillMode: Image.PreserveAspectCrop onActiveFocusChanged: backg.source=Imagen.source }
main.cpp file:
#include <QtQml/QQmlProperty> #include <QQuickWindow> #include <QTime> #include <QString> int main(int argc, char *argv[]) { QTime time=QTime::currentTime(); QDate date=QDate::currentDate(); QString day=date.toString("ddd, dd of mmm of yyyy"); QString hour=time.toString("h:m:s ap"); QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); QQmlApplicationEngine engine; engine.load(QUrl(QStringLiteral("qrc:/start.qml"))); qmlRegisterType<Image>("PTrans.class.Imagen", 1, 0, "Imagen"); QQuickWindow *backg = (QQuickWindow *)engine.rootObjects().first(); if (backg) backg->setProperty("source","2.jpg"); if (engine.rootObjects().isEmpty()) return -1; return app.exec(); }
-
Why do you want to change the property of QML object from c++ ? We can help you based on this. It is not a good practice to change property of QML object from C++. There are ways to do it. Not advisable.
-
The thing is that I need to process all the data trough c++ and qml is just for the visual of the program, for example: read a c++ variable and put it data in a label on qml. I know that its harder than the normal way, but my teacher wants it that way.
-
@NerdTronik
Hi
Having c++ do the heavy lifting and use QML as GUI is a good concept and
also very normal.
However, you should not directly try to access the QML Objects from c++ but rather
make the c++ data available to QML.
http://doc.qt.io/qt-5/qtqml-cppintegration-topic.html