How to convert a pointer value to QString?
Why not simply use QString & QString::sprintf ( const char * cformat, ... )
QString t;
// QString::sprintf adds 0x prefix
t.sprintf("%08p", ptr);
Using QString::arg():
MyClass *ptr = new MyClass();
QString ptrStr = QString("0x%1").arg((quintptr)ptr,
QT_POINTER_SIZE * 2, 16, QChar('0'));
It will use the correct type and size for pointers (quintptr
and QT_POINTER_SIZE
) and will always prefix "0x"
.
Notes:
To prefix the value with zeros, the fourth parameter needs to be QChar('0')
.
To output the correct number of digits, QT_POINTER_SIZE
needs to be doubled (because each byte needs 2 hex digits).
QTextStream appears to offer the functionality you seek, and operates simply on a void*
.
const void * address = static_cast<const void*>(ptr);
QString addressString;
QTextStream addressStream (&addressString);
addressStream << address;
qDebug() << addressString;
Unlike the other approaches, it does not reference notions like the particular number "8" or casting to "qlonglong". Seems less worrisome, and is much like the prescribed method for std::string (though without getting std::string
conversions involved)