c++stringqtqstringqdebug

How to get string representation of common Qt5 types like QOpenGLContext?


NOTE: This is a rather naïve question on purpose.

During debugging and logging in a Qt5 C++ application it is useful to print the value of internal variables, and in Qt the common way is to use qDebug() with friends like this:

qDebug()<<"The value was: "<< myVar;
// Usually works well even for built-in Qt types

This seems to work for many built-in Qt5 specific types, and even pointers as well, however in the cases where instead of outputting a log, we are in fact building a string this becomes much more cumbersome.

QString myString= "The value was: "+myVar;
// Usually doesn't work well for built-in Qt types

So the question is, what is a good general way to get the equivalent string representation of built-in Qt types as you would get from streaming them to qDebug()?

Or "what is the equivalent to Java toString() for Qt types"?


Solution

  • From QDebug class documentation I could find that it has constructor

    QDebug::QDebug(QString *string)
    

    Constructs a debug stream that writes to the given string

    So this should work:

    QString myString;
    QDebug stream(&myString);
    stream <<"The value was: "<< myVar;