Overloading QDebug in QtObject subclass
-
Hello,
I want to debug out some information about a custom QtObject-subclass. Therefore I'm using the operator<< mechanism as described here.This doesn't work for me.
My Test-Implementation:
DebugClass.h
#ifndef DEBUGCLASS_H #define DEBUGCLASS_H #include <QObject> class DebugClass : public QObject { Q_OBJECT public: explicit DebugClass(QObject *parent = nullptr); int getX() const; signals: private: int x; }; QDebug operator<< (QDebug , const DebugClass &); #endif // DEBUGCLASS_H
DebugClass.cpp
#include "DebugClass.h" #include <QDebug> DebugClass::DebugClass(QObject *parent) : QObject{parent} { x = 42; } QDebug operator<<(QDebug dbg, const DebugClass &info) { dbg.nospace() << "This is x: " << info.getX(); return dbg.maybeSpace(); } int DebugClass::getX() const { return x; }
Using the DebugClass:
auto debugClass = new DebugClass(); qDebug() << "Test DebugClass:" << debugClass;
This gives me the following output:
"Test DebugClass: DebugClass(0x2af8d9e1250)"
The <<-Operator is never called.
Can someone help me with that?thanks,
Tobias -
@Tobias-Fensch said in Overloading QDebug in QtObject subclass:
"Test DebugClass: DebugClass(0x2af8d9e1250)"
The <<-Operator is never called.
It's not called because you pipe the pointer to your type, but the operator<<() expects a value (const reference) of your type.
To make C++ call your operator<<() make sure to de-reference the pointer.
-
Hello,
I want to debug out some information about a custom QtObject-subclass. Therefore I'm using the operator<< mechanism as described here.This doesn't work for me.
My Test-Implementation:
DebugClass.h
#ifndef DEBUGCLASS_H #define DEBUGCLASS_H #include <QObject> class DebugClass : public QObject { Q_OBJECT public: explicit DebugClass(QObject *parent = nullptr); int getX() const; signals: private: int x; }; QDebug operator<< (QDebug , const DebugClass &); #endif // DEBUGCLASS_H
DebugClass.cpp
#include "DebugClass.h" #include <QDebug> DebugClass::DebugClass(QObject *parent) : QObject{parent} { x = 42; } QDebug operator<<(QDebug dbg, const DebugClass &info) { dbg.nospace() << "This is x: " << info.getX(); return dbg.maybeSpace(); } int DebugClass::getX() const { return x; }
Using the DebugClass:
auto debugClass = new DebugClass(); qDebug() << "Test DebugClass:" << debugClass;
This gives me the following output:
"Test DebugClass: DebugClass(0x2af8d9e1250)"
The <<-Operator is never called.
Can someone help me with that?thanks,
Tobias@Tobias-Fensch Did you put operator<< into a header file and did you include this header file where you are trying to use operator<<?
-
@Tobias-Fensch said in Overloading QDebug in QtObject subclass:
"Test DebugClass: DebugClass(0x2af8d9e1250)"
The <<-Operator is never called.
It's not called because you pipe the pointer to your type, but the operator<<() expects a value (const reference) of your type.
To make C++ call your operator<<() make sure to de-reference the pointer.