Embedding C++ Objects into QML with Context Properties
Solved
QML and Qt Quick
-
I am trying an example code and able to execute it successfully. But iam unable to see the result. Here is my program for your reference. I am a beginner in this field, hope some changes and explaination helps me to advance and understand.
applicationdata.cpp file
#include "applicationdata.h" ApplicationData::ApplicationData() { } Q_INVOKABLE QDateTime ApplicationData::getCurrentDateTime() const { return QDateTime::currentDateTime(); }
applicationdata.h file
#ifndef APPLICATIONDATA_H #define APPLICATIONDATA_H #include <QDateTime> #include <QObject> class ApplicationData : public QObject { Q_OBJECT public: ApplicationData(); public slots: Q_INVOKABLE QDateTime getCurrentDateTime() const; }; #endif // APPLICATIONDATA_H
and main.cpp file
#include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQuickView> #include "applicationdata.h" #include <QQmlContext> int main(int argc, char *argv[]) { QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); QQuickView view; ApplicationData data; view.rootContext()->setContextProperty("applicationData",&data); view.setSource(QUrl::fromLocalFile("MyItem.qml")); view.show(); return app.exec(); }
MyItem.qml file
import QtQuick 2.0 Text { text: applicationData.getCurrentDateTime() }
I can see a blank output when i execute it instead i want to see current date and time.
-
Yes, got it. Changed the path to
view.setSource(QUrl(QStringLiteral("qrc:/MyItem.qml")));
It is working.
-
@JennyAug13 hi, you also can use QML Date object
-
@LeLev May i ask, how to do it with qml date object
-
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
property date mydate : new Date();
Component.onCompleted: {
print(mydate.toLocaleDateString())
}
}