If you need some kind of log from QML source code, you can create your own QML Logger object. This object will use your C ++ registration system to log in wherever you want and at your preferred level. To achieve this result, first create a C ++ class that inherits from QQuickItem , for example:
QmlLogger.hpp
#include <QQuickItem> class QmlLogger : public QQuickItem { Q_OBJECT public: explicit QmlLogger(QQuickItem *iParent = 0); // Q_INVOKABLE log method will be called by Qml source. Q_INVOKABLE void log(unsigned int iLogLevel, const QString& iDataToLog) const; enum Level { Error = 0, Warning, Info, Debug, Trace }; Q_ENUMS(Level) private: YourLogger mYourLogger; // YourLogger is your system to log on C++ world };
QmlLogger.cpp
#include <QmlLogger.hpp> // Your Constructor // Implementation of log method callable from Qml source void log(unsigned int iLogLevel, const QString& iDataToLog) const { switch(iLogLevel) { case Error: // ERROR // use you logger to log iDataToLog at error level break; case Warning: // WARNING // use you logger to log iDataToLog at warning level break; case Info: // INFO // use you logger to log iDataToLog at info level break; case Debug: // DEBUG // use you logger to log iDataToLog at debug level break; case Trace: // TRACE // use you logger to log iDataToLog at trace level break; } }
Now you need to register a new object to make it available for the QML mechanism, then we must use the qmlRegisterType template function from the QQmlEngine class. Use this function after entering the main Qt loop, for example, as follows:
int typeId = qmlRegisterType<QmlLogger>("QmlLogger", 1, 0, "Logger"); // if typeId is 0 => Error Q_ASSERT(typeId);
In C ++, we are done. Now in the QML source we can use the new object in such a simple way.
import QmlLogger 1.0 Logger{ id: logger } function aFunctionThatYouWantToDebug(iArgumentOne, iArgumentTwo){ // logging logger.log(Logger.Debug, "Entering function aFunctionThatYouWantToDebug(" + iArgumentOne + ", " + iArgumentTwo + ")") // body of function ... }
Calling the log method in the QML source is equivalent to calling the log method in the C ++ QmlLogger , which writes to your log file, data is logged.
Alessandro
source share