[Solved] Printable Object
-
Hi everyone,
I need made a custom printable QObject printable, I follow the qt "doc":http://qt-project.org/doc/qt-4.8/custom-types.html#making-the-type-printabledoc but can't use this successfully.
@MyObject : public QObject
{
Q_OBJECT
MyObject() : m_str("Hello world") {}
MyObject(const MyObject &o) : m_str(o.m_str) {}
~MyObject() {}private:
QString m_str;}
Q_DECLARE_METATYPE(MyObject)QDebug operator <<(QDebug &, const MyObject &); /* trivial definition in *.cpp file */
@If I try to use qDebug() << MyClass I've got: no match for 'operator<<' in 'QDebug()() << MyClass'
@/* main.cpp */
MyClass m;
qDebug() << m;@I need print my custom object for debug purposes.
Thank you in advice.
BR,
-
Hi,
first of all, MyClass != MyObject.
Are you sure, the code is the one you use?
I ask because I get compile errors others then the one you had.
This code works for me:@
#include <QObject>
#include <QDebug>class MyObject : public QObject
{
Q_OBJECT
public:
MyObject() : m_str("Hello world") {}
MyObject(const MyObject &o) : m_str(o.m_str) {}
~MyObject() {}private:
QString m_str;
friend QDebug& operator << (QDebug& debug, const MyObject& myObj);
};Q_DECLARE_METATYPE(MyObject)
inline QDebug& operator << (QDebug& debug, const MyObject& myObj)
{
debug.nospace() << '(';
debug << "MyObject(" << myObj.m_str << ")";
return debug.space();
}int main(int argc, char *argv[])
{
MyObject m;
qDebug() << m;return 0;
}
@
-
Hi Gerolf,
Thank for your reply.
- Yes, MyClass != MyObject (I'm sorry, it was a typographic mistake).
- I have found the error (but I can't understand), your definition don't work for me:
When we see this definition anything is wrong, it's a simple operator overload, but don't work when use & in QDebug parameter (dbg reference), I have to eliminate this from you code and it work.
@Debug &operator <<(QDebug dbg, const MyObject &myObj)@
But I can't understand why can't pass QDebug like reference.
Thank you Gerolf.
BR,