Logging from QML and C++
When starting work on a new project, one of the first things you will want to setup is the ability to log to output for debugging purposes.
Unfortunately, with the current version of Cascades you have to do a little bit of work first to set this up.
However, you can perform logging that is visible in the “Console” window of the Momentics IDE.
In order to be able to view your logs, you first need to register a message handler in C++.
Do this in the main entry point to your application:
std::fprintf(stdout, “%s\n”, msg);
std::fflush(stdout);
}
int main(int argc, char *argv[]) {
Application app(argc, argv);
qInstallMsgHandler(messageLogger);
new LoggingTest(&app);
return app.exec();
}
Now when you make a call to log text from either QML or C++, the messageLogger function will be called, and in the above example the message will be written to stdout using the fprintf function.
Logging from QML
Logging from QML is achieved using the console javascript object that is implicitly available from QML. For example, the following QML button will log the message “Button clicked!” when clicked
text: “QML Log Message”
onClicked: {
console.log(“Button clicked!”);
}
}
Logging from C++
Standard logging from C++ is achieved using the qDebug() function as follows:
In addition to qDebug(), you can also use any one of the qWarning(), qCritical() and qFatal() functions which return QDebug objects for the corresponding message types. And as an alternative to using the insertion operator, you can pass along formatted output.
For example:
A more general/flexible message handler that handles all the different message types may could look as follows:
{
switch (type) {
case QtDebugMsg:
std::fprintf(stdout, “Debug: %s\n”, msg);
break;
case QtWarningMsg:
std::fprintf(stdout, “Warning: %s\n”, msg);
break;
case QtCriticalMsg:
std::fprintf(stderr, “Critical: %s\n”, msg);
break;
case QtFatalMsg:
std::fprintf(stderr, “Fatal: %s\n”, msg);
std::abort();
break;
}
}

















































