Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overload operator<< for qDebug

I'm trying to create more useful debug messages for my class where store data. My code is looking something like this

#include <QAbstractTableModel>
#include <QDebug>

/**
  * Model for storing data. 
  */
class DataModel : public QAbstractTableModel {
    // for debugging purposes
    friend QDebug operator<< (QDebug d, const DataModel &model);

    //other stuff
};

/**
  * Overloading operator for debugging purposes
  */
QDebug operator<< (QDebug d, const DataModel &model) {
    d << "Hello world!";
    return d;
}

I expect qDebug() << model will print "Hello world!". However, there is alway something like "QAbstractTableModel(0x1c7e520)" on the output.

Do you have any idea what's wrong?

like image 747
izidor Avatar asked Apr 20 '10 18:04

izidor


3 Answers

I know it long time now, but just to be documented and to help any other people who eventually come here having the same doubt, the easiest way to get qDebug() << working with your own class printing something like "Hello World" or whatever else, is to implement implicit conversion of your class to a printable type, like QString (which is well supported by QDebug).

class Foo {
public:
   Foo() { }
   operator QString() const { return <put your QString here>; }   

};
like image 79
Vinícius A. Jorge Avatar answered Nov 19 '22 08:11

Vinícius A. Jorge


In your example, qDebug() prints the address of your variable, which is the default behavior for unknown types.

In fact, there seem to be two things you have to take care of:

  • Get the item by value (and eugen already pointed it out!).
  • Define the overloading operator before you use it, put its signature in the header file, or define it as forward before using it (otherwise you will get the default "qDebug() <<" behavior).

This will give you:

QDebug operator<< (QDebug d, const DataModel &model) {
    d << "Hello world!";
    return d;
}
DataModel m;
qDebug() << "m" << m;

or

QDebug operator<< (QDebug d, const DataModel &model);

DataModel m;
qDebug() << "m" << m;

QDebug operator<< (QDebug d, const DataModel &model) {
    d << "Hello world!";
    return d;
}

I've learned it the hard way, too...

like image 34
a.l.e Avatar answered Nov 19 '22 10:11

a.l.e


After an hour of playing with this question I figured out model is pointer to DataModel and my operator << takes only references.

like image 12
izidor Avatar answered Nov 19 '22 08:11

izidor