Posted October 24, 2012 by Rapid Yvonne in Tutorials and Tips
 
 

Logging from QML and C++

cascades builder
cascades builder

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:

void messageLogger(QtMsgType type, const char *msg) {
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

Button {
text: “QML Log Message”
onClicked: {
console.log(“Button clicked!”);
}
}

Logging from C++

Standard logging from C++ is achieved using the qDebug() function as follows:

qDebug() << “Message logged from C++”;

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:

qWarning(“A warning message with some args: %s %d”, “The meaning of life is “, 42);

A more general/flexible message handler that handles all the different message types may could look as follows:

void messageLogger(QtMsgType type, const char *msg)
{
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;
}
}
Did you enjoy this article? If so, we’d love to hear your thoughts on the Forums or on our Facebook page. Get more articles instantly on your BlackBerry smartphone with our Free BlackBerry 10 App.

Via

Enjoy this article? Share it with others.

  • Facebook
  • Twitter
  • StumbleUpon
  • LinkedIn
  • Digg
  • Pinterest
  • Google Plus
  • Tumblr
  • Reddit
  • Instapaper
  • Delicious
  • Email
  • Print