简体   繁体   中英

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"?

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;

The format and contents of Qt debug output are not a part of the API. They can change at any time. You will have to audit the output each and every time you update Qt, otherwise you must not depend on it other than for debugging. That's why the APIs make it purposefully cumbersome to convert between debug output and strings.

Instead, implement your own QTextStream operators for types that you need, and use the stream to build the strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM