7

在 Qt/C++ 中有 QT_DEBUG 定义宏来知道它何时在调试或发布时被编译。

有什么方法可以知道应用程序是否在 QML 文件中以调试或发布模式运行?

4

2 回答 2

15

您可以使用上下文属性将 C++ 对象公开给 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
    }
}

纯粹从 QML 中确定这一点是不可能的。

于 2014-04-07T07:47:41.257 回答
3

您需要在运行时或编译时知道它吗?宏在编译时使用,QML 在运行时执行,所以编译后的应用程序在“调试”和“发布”之间没有区别。

解决方案:

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;
}
于 2014-04-07T07:49:16.357 回答