Logging custom objects to QDebug
When you are debugging complex objects, it is nice to output their current members' value to qDebug()
. In other languages (such as Java), you may have encountered the toString()
method or equivalent, which is very convenient.
Sure, you could add a function void toString()
to each object you want to log in order to write code with the following syntax:
qDebug() << "Object content:" << myObject.toString()
There must be a more natural way of doing this in C++. Moreover, Qt already provides this kind of feature:
QDate today = QDate::currentDate(); qDebug() << today; // Output: QDate("2016-10-03")
To achieve this, we will rely on a C++ operator overload. This will look very similar to what we did with QDataStream
operators in Chapter 10, Need IPC? Get Your Minions to Work.
Consider a struct Person
:
struct Person { QString name; int age; };
To add the ability to properly output to QDebug
, you...