简体   繁体   English

如何获取常见Qt5类型(例如QOpenGLContext)的字符串表示形式?

[英]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: 在调试和登录Qt5 C ++应用程序期间,打印内部变量的值非常有用,在Qt ,常见的方法是将qDebug()与这样的朋友一起使用:

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. 这似乎适用于许多内置的Qt5特定类型,甚至也适用于指针,但是在不输出日志的情况下,实际上我们正在构建一个字符串,这种情况变得非常麻烦。

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()? 因此,问题是,与将内置流类型传输到qDebug()所获得的等效的内置Qt类型字符串表示法一样,有什么通用的好方法?

Or "what is the equivalent to Java toString() for Qt types"? 还是“ Qt类型与Java toString()等效”是什么?

From QDebug class documentation I could find that it has constructor QDebug类文档中,我可以发现它具有构造函数

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. Qt调试输出的格式内容不是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. 每次更新Qt时,您都必须审核输出,否则,除调试外,您不得依赖它。 That's why the APIs make it purposefully cumbersome to convert between debug output and strings. 这就是API故意在调试输出和字符串之间进行转换的麻烦。

Instead, implement your own QTextStream operators for types that you need, and use the stream to build the strings. 而是,为所需的类型实现自己的QTextStream运算符,然后使用流构建字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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