[Interest] Replace QML console object

Furkan Uzumcu furkanuzumcu at gmail.com
Fri Jul 24 20:36:53 CEST 2020


I know of two ways you can go about doing this.

1- Add new function prototypes to console object and use those.

> console.log2 = (message) => console.log("[LOG] ", message)
> console.log2(“Here’s a message”)
>> // [LOG] Here’s a message

2- You can register your own logger as a context property and use that.

// main.cpp
> struct MyLogger : public QObject
> {
> Q_OBJECT
>
> public:
> Q_INVOKABLE void log(const QString& message) {
> qDebug() << "[LOG] " << message;
> }
> };

> engine.rootContext()->setContextProperty("console", &logger);

// main.qml

> console.log("Hello world.")

One down side with the second approach is that I don’t know of any way you can remove the logger once you register it. So, it maybe useful for when you are creating types from the QML side and want to only use the custom logger in certain contexts. You may be able to store the default logger somewhere and switch back to it, but I’m sure about that.

The solution you provide in the StackOverflow answer is essentially approach #1. I doubt that you would be able to do that because it likely doesn’t provide a writer for that property. But there’s nothing stopping you from adding a new property to it.

For example, If you apply the second approach, you can easily do this as well:

> console.log("Hello world.")
> console.info2 = (message) => console.log("[INFO] " + message)
> console.info2("Hello world.")

But if you do the following:

> console.log = (message) => root.color = message
> console.log("red")
> // qrc:/main.qml:13: TypeError: Cannot assign to read-only property "log"

You’ll get an error message. I don’t know how the default console object is implemented, so I unfortunately don’t have technical insight as to why it doesn’t throw an error but simply failed silently.

Regards,
Furkan Üzümcü
On Jul 6, 2020, 09:31 -0400, Richard Weickelt <richard at weickelt.de>, wrote:
> I want to replace QML's console object with a custom implementation.
>
> I have tried to replace the "console" property in the global object with not
> luck.
> I have tried to replace the method properties of the global console object
> with no luck (as described here:
> https://stackoverflow.com/questions/26909578/replace-logging-backend-for-console-debug-console-warn).
>
> Is there any way to achieve that without touching the global logger backend?
> That would interfere with QTest & friends which I want to avoid.
>
> Thanks
>
> _______________________________________________
> Interest mailing list
> Interest at qt-project.org
> https://lists.qt-project.org/listinfo/interest
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20200724/9c1a4d55/attachment.html>


More information about the Interest mailing list