[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,



  • Edit: I'm really sorry, I tried to answer your question but it happened that I did it extremely wrong, I'll search for a possible solution and if I find anything out I come back here and edit my post to help you.

    Sorry again hehe.



  • 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.

    1. Yes, MyClass != MyObject (I'm sorry, it was a typographic mistake).
    2. 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,


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.