本文介绍了交替使用 std::string 和 QString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我正在为图形和 GUI 组件工作的软件系统中广泛使用 Qt.然而,对于大多数内部算法和数据处理来说,Qt 的作用较小.

I use Qt extensively in a software system I'm working on for graphical and GUI components. However, for most internal algorithms and processing of data Qt plays a smaller role.

我经常需要将 std::string 转换为 QString,反之亦然.我的倾向是尽可能多地使用 std::string 并在需要将字符串传递给 Qt 类(例如与文件系统一起使用的类)时使用 QString.

I'll often run into the need to convert from std::string to QString or visa versa. My inclination is to use std::string as much as possible and use QString only when I need to pass strings to Qt classes like those that work with the file system.

当我今天早上编程时,我突然想到在我的代码中同时使用 std::string 和 QString 可能是一个糟糕的设计.我应该完全切换到 QString 吗?有没有其他人遇到过这种设计选择?

As I was programming this morning, it hit me that it may be bad design to have both std::string and QString sprinkled throughout my code. Should I completely switch to QString? Has anyone else run into this design choice?

Qt 提供了许多与 STL 相同的功能,但我仍然犹豫是否要完全切换,因为 Qt 的标准化和稳定性较低.

Qt provides a lot of the same functionality of STL, but I'm still hesitant switching completely since Qt is less standardized and stable.

推荐答案

是的,我以前也遇到过这种情况.我工作的程序始终使用 Qt,但我必须将它连接到一个需要 std::string 的库.QString 的好处是它明确使用了 Unicode,而 C++ 标准库对编码不做任何保证.

Yes, I've had this situation before. The program I worked on used Qt throughout, but I had to hook it up to a library that expected std::string. The benefit of QString is that it explicitly uses Unicode, while the C++ standard library makes no guarantees about encoding.

解决方案是在这个库的边界处转换

The solution was to convert at the boundary of this library with

QString toQString(std::string const &s)
{
    return QString::fromUtf8(s.c_str());
}

std::string fromQString(QString const &s)
{
    return std::string(s.toUtf8().data());
}

因为库产生了包含 UTF-8 的 std::string.

since the library produced std::string's containing UTF-8.

您似乎想要的是完全相反的:始终使用 std::string 并在 Qt 边界进行转换.这似乎完全没问题;它比总是使用 QString 需要更多的工作,但是当你需要一个非 QString 接受库时,你必须付出努力,而你的非-GUI 组件不依赖于 Qt(欢呼!).

What you seem to want is the exact opposite: use std::string throughout and convert at the Qt boundary. That seems perfectly ok; it takes a bit more work than always using QString, but you'll have to put in effort when you need a non-QString-accepting library anyway, and your non-GUI components don't depend on Qt (hurrah!).

这篇关于交替使用 std::string 和 QString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 03:01