Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a QML category for console.log

Tags:

c++

qt

qml

I'm new to the Qt/QML topic and I'm trying to install a logging handler in my c++ business logic. The following code snipet installs a handler and sets a special category:

    int main(int argc, char *argv[])
    {
       qInstallMessageHandler(myMessageOutput);
       QLoggingCategory mainEx("main.ex");

       qCDebug(mainEx) << "debug message";
       ...
    }

The result is a call from the Qt backend to the following installed message handler:

void myMessageOutput(QtMsgType type, const QMessageLogContext &context,
                     const QString &msg)
{
   ...
}

In Qt 5 it is also possible to write debug messages directly in in QML with:

console.debug("debug message")

But the 'cateory' in QMessageLogConext is always 'qml'. Is it possible to set another category directly in QML?

like image 696
fischeth Avatar asked Oct 26 '15 14:10

fischeth


People also ask

How do I connect QML to C++?

Connecting to QML Signals All QML signals are automatically available to C++, and can be connected to using QObject::connect() like any ordinary Qt C++ signal. In return, any C++ signal can be received by a QML object using signal handlers.

How do you use QML in Qt?

Creating and Running QML Projects For simple UI files such as this one, select File > New File or Project > Application (Qt Quick) > Qt Quick Application - Empty from within Qt Creator. Pressing the green Run button runs the application. You should see the text Hello, World! in the center of a red rectangle.

What is component onCompleted in QML?

Emitted after component "startup" has completed. This can be used to execute script code at startup, once the full QML environment has been established. The corresponding handler is onCompleted. It can be declared on any object. The order of running the onCompleted handlers is undefined.


1 Answers

Starting with Qt 5.8, categorized logging available out of the box in QML.

A logging category can be passed to console.log() and friends as the first argument. If supplied to to the logger the LoggingCategory's name will be used as Logging Category otherwise the default logging category will be used.

import QtQuick 2.8

Item {
    LoggingCategory {
        id: category
        name: "com.qt.category"
    }

    Component.onCompleted: {
      console.log(category, "message");
    }
}
like image 199
Nikita Krupenko Avatar answered Sep 28 '22 10:09

Nikita Krupenko