Qt6 topics merged with General

How does the "toString" method of qt data structures work?

  • I found myself trying to save the textual representation of a QVariantMap (QMap<QString, QVariantMap>> actually) like as if I were to write
    qDebug() << myMap
    which yields the correct text data put to the console, but instead have the result in a file. I tried with QDataStream class but it can only handle binary form, I managed to do it finally like this:
    QDebug outDebug(&file);
    outDebug << myMap;
    But it really bothers me that I have no idea what is going on behind the scenes. I assume either QDebug & QDebug::operator<<(const QByteArray & b) or QDebug & QDebug::operator<<(const QString & s) functions are called after an implicit conversion, but how does that implicit conversion work?

    Also I have a custom (non-QObject)! class that is among the stored QVariants and it's textual repesentation is an empty string. Is there a way to customize that?

  • YourClass
    friend QDataStream & operator << (QDataStream & out, const YourClass& t)
    out << t._nom;
    return out;

  • That'll work, ty, but how come a QDebug instance can decompress the binary to textual? And how does one do it without QDebug instance?

  • And actually I can't make your code snippet work. I implemented the friend operator method as described by you and doc but it's not called like it should be.

    QVariant(BitPattern, )
    empty string................^

  • Lifetime Qt Champion


    Have a look at the QDebug documentation, there's an example on how to write a debug stream operator for your custom type.

  • Aha, I see, somehow I skipped trough that paragraph of the doc, thanks!

Log in to reply