Search code examples
qtqstringboost-filesystem

How to convert between `boost::filesystem::path` and `QString`?


When wrapping a Qt UI around back-end code using boost::filesystem one frequently needs to convert boost::filesystem::path to QString and vice versa.

What is the best way way to do these conversions that:

  1. Is cross-platform
  2. Losslessly preserves encoding
  3. Produces QStrings containing regular slashes on all platforms, as is Qt's policy.
  4. Is efficient and avoids unnecessary copies

Solution

  • This is what I'm currently using, but suggestions for improvements are very much welcome.

    boost::filesystem::path PathFromQString(const QString & filePath)
    {
    #ifdef _WIN32
        auto * wptr = reinterpret_cast<const wchar_t*>(filePath.utf16());
        return boost::filesystem::path(wptr, wptr + filePath.size());
    #else
        return boost::filesystem::path(filePath.toStdString());
    #endif
    }
    
    QString QStringFromPath(const boost::filesystem::path & filePath)
    {
    #ifdef _WIN32
        return QString::fromStdWString(filePath.generic_wstring());
    #else
        return QString::fromStdString(filePath.native());
    #endif
    }