Printing Custom Qt Types with qDebug()
When you define your own C++ types for a Qt application, you want to print their values with qDebug()
, qWarning()
or qCritical()
eventually.
auto frame1 = QCanBusFrame{0x18ef0201U, QByteArray::fromHex("018A010000000000")};
qDebug() << "frame1 =" << frame1;
The C++ compiler will complain with this error message:
error: no match for ‘operator<<’ (operand types are ‘QDebug’ and ‘QCanBusFrame’)
The error message tells you to write your own output operator for the QDebug
stream and for QCanBusFrame
.
A custom C++ type that wants to play nicely with Qt should always define a QDebug
output operator. Even the developers of the Qt library seem to forget it sometimes, as the example of QCanBusFrame
shows.