Pregunta

At Qt/C++ there is QT_DEBUG define macro to know when it is compiled at debug or release.

Is there any method to know if is the application running in debug o release mode inside a QML file?

¿Fue útil?

Solución

You can use context properties (or QQmlApplicationEngine::setInitialProperties() since Qt 5.14) to expose C++ objects to QML:

#include <QtGui/QGuiApplication>
#include <QQmlContext>
#include <QQuickView>
#include "qtquick2applicationviewer.h"

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

    QtQuick2ApplicationViewer viewer;
#ifdef QT_DEBUG
    viewer.rootContext()->setContextProperty("debug", true);
#else
    viewer.rootContext()->setContextProperty("debug", false);
#endif
    viewer.setMainQmlFile(QStringLiteral("qml/quick/main.qml"));
    viewer.showExpanded();

    return app.exec();
}

main.qml:

import QtQuick 2.2

Item {
    id: scene
    width: 360
    height: 360

    Text {
        anchors.centerIn: parent
        text: debug
    }
}

It's not possible to determine this purely from within QML.

Otros consejos

You need to know it in runtime or in compile time? Macros are used in compile time, QML is executed in runtime, so there are no difference for compiled application between "debug" and "release".

Solution:

Create a class with const property declared in next way:
class IsDebug : public QObject
{
  QOBJECT
  Q_PROPERTY( IsDebug READ IsCompiledInDebug ) // Mb some extra arguments for QML access
public:
  bool IsCompiledInDebug() const { return m_isDebugBuild; }
  IsDebug()
#ifdef QT_DEBUG
  : m_isDebugBuild( true )
#else
  : m_isDebugBuild( false )
#endif
  {}
private:
  const bool m_isDebugBuild;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top