最近重拾QT,发现百度能搜索到的东西甚少,所以上StackOverFlow上查了一些资料,觉得对自己有用的就做了记录,方便以后查看,本篇基于Qt4.8.5,windows平台。
问题1. 如何将整数型转成QString
链接:https://stackoverflow.com/questions/3211771/how-to-convert-int-to-qstring
解决方法:
使用 QString::number()方法
1 int i = 42; 2 QString s = QString::number(i);
如果你需要将数字放入字符串里面,建议这样写:
1 int i = 42; 2 QString printable = QString::fromLatin1("数字是 %1. ").arg(i);
问题2 如何将QString转成string
链接:https://stackoverflow.com/questions/4214369/how-to-convert-qstring-to-stdstring
解决方法:
1 QString qs; 2 // do things 3 qDeubug() << qs.toStdString();
如果不考虑特殊字符的话,直接使用QString::toStdString()是没有问题的,并且在Qt5.0以后QString::toStdString()会使用QString::toUtf8()来进行转换;
但是考虑编码问题的话,比如你的字符串是这样的QString s = QString::fromUtf8("árvízt?r? tük?rfúrógép áRVíZT?R? TüK?RFúRóGéP"),建议使用:
1 QString qs; 2 3 string current_locale_text = qs.toLocal8Bit().constData();
问题3 Qt容器和STL容器的选择
链接:https://stackoverflow.com/questions/1668259/stl-or-qt-containers
答案中提到了很多Qt容器的优点,比如更多的功能,STL风格和Java风格的遍历方式,更可靠、稳定的实现,更少的占用内存等等,个人感觉Qt容器的优势是简单、安全、轻量级,比较赞同第二高赞的回答:
This is a difficult to answer question. It can really boil down to a philosophical/subjective argument. That being said... I recommend the rule "When in Rome... Do as the Romans Do" Which means if you are in Qt land, code as the Qt‘ians do. This is not just for readability/consistency concerns.
Consider what happens if you store everything in a stl container then you have to pass all that data over to a Qt function.
Do you really want to manage a bunch of code that copies things into/out-of Qt containers. Your code is already heavily dependent on Qt,
so its not like you‘re making it any more "standard" by using stl containers.
And whats the point of a container if everytime you want to use it for anything useful, you have to copy it out into the corresponding Qt container?
渣译如下:
入乡随俗。如果你使用Qt平台,就尽量使用带有Qt特性的容器,这不仅仅是出于稳定性/一致性的考虑。试想一下如果你将所有的数据都存储在Stl容器内然后你想把他们传给一个Qt方法那有多糟糕(其实没他说的那么可怕)。你真的想要将东西拷来拷去吗?如果你的工程已经重度依赖Qt了,那么仅仅为了标准去使用stl容器,就没有意义了。
问题4:检查一个文件夹是否存在
链接:https://stackoverflow.com/questions/2241808/checking-if-a-folder-exists-and-creating-folders-in-qt-c
解决方法:
检查文件夹是否存在:
QDir("Folder").exists();
创建一个新的文件夹:
QDir().mkdir("Folder");
检查一个文件夹是否存在不存在则创建此文件夹,可以这样写:
1 QDir dir("Folder"); 2 if (!dir.exists()) { 3 dir.mkpath("."); 4 }