Convert CFStringRef to QString
Question
cross platform c++ header file. separate c++ file for each platform: windows, linux, mac. Deals with platform specific implementation of enumerating windows.
on the mac side: I have a CFStringRef populated. the header file defines a QString object. I need to pass the contents of the CFStringRef to the QString.
How can this be achieved?
Solution
This is the static function used internally by Qt (from src/corelib/kernel/qcore_mac.cpp):
QString QCFString::toQString(CFStringRef str)
{
if (!str)
return QString();
CFIndex length = CFStringGetLength(str);
if (length == 0)
return QString();
QString string(length, Qt::Uninitialized);
CFStringGetCharacters(str, CFRangeMake(0, length), reinterpret_cast<UniChar *>
(const_cast<QChar *>(string.unicode())));
return string;
}
Update (2020): nowadays use QString::fromCFString() as @ehopperdietzel suggested in his answer.
OTHER TIPS
You can use the fromCFString() method included in the QString class:
CFStringRef str = CFSTR("Hello World!");
QString convertedStr = QString::fromCFString(str);
I didn't try it but I would do something like this:
QVector<UniChar> uniChars(CFStringGetLength(cfStr));
CFStringGetCharacters(cfStr, CFRangeMake(0, CFStringGetLength(cfStr), uniChars.data());
QString qString = QString::fromUtf16(uniChars.data(), uniChars.size());
To avoid allocation of the UniChar buffer, you can try CFStringGetCharactersPtr()
first and use the buffer one as a fall back.