PDA

View Full Version : Accessing QGuiApplication derived class properties from QML



mentalmushroom
30th August 2016, 17:13
I am trying to pass an instance of Application class, which is derived from QGuiApplication, to QML and access its properties there. For the reasons I don't understand it tells the property is undefined: "Unable to assign [undefined] to QString". At the same time properties inherited from QGuiApplication can be accessed without any problem, e.g. app.applicationName works fine.

Here is the QML code (main.qml). The Text component was supposed to show the application version.


import QtQuick 2.7
import QtQuick.Controls 2.0

ApplicationWindow
{
title: "another title"
visible: true
width: 1000
height: 800

Rectangle
{
color: "lightsteelblue"
anchors.fill: parent

Text
{
anchors.centerIn: parent
//text: app.updatesAvailable ? "Updates Are Available" : "My Application"
//text: app.updatesAvailable
text: app.versionString
//text: app.applicationName
//text: testObj.title
}
} // Rectangle
} // ApplicationWindow



This is how the application instance is passed to QML (main.cpp):


#include "application.h"
#include <QQmlContext>

int main(int argc, char *argv[])
{
Application app(argc, argv);

QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("app", &app);
engine.load(QUrl("qrc:///qml/main.qml"));

return app.start();
}


And, finally, the Application class declaration (application.h) looks like this:


#ifndef APPLICATION_H
#define APPLICATION_H

#include <QGuiApplication>

class Application: public QGuiApplication
{
Q_PROPERTY(bool updatesAvailable READ checkForUpdates)
Q_PROPERTY(QString versionString READ getVersionString CONSTANT)

public:
Application(int &argc, char **argv);
~Application();

bool isRunning() const { return false; }
bool checkForUpdates() { return true; }

QString getVersionString() const { return "2.7"; }

int start();
}; // Application

#endif // APPLICATION_H


Any clues?

anda_skoa
30th August 2016, 19:20
Missing the Q_OBJECT macro.

Also properties exposed to QML need to be either CONSTANT or have an associated NOTIFY signal.

Cheers,
_