macosqtcfstring

Convert CFStringRef to QString


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.