1. 程式人生 > >QT常見問題和解決方案整理

QT常見問題和解決方案整理

cpp recommend log 實現 utf tro int 發現 ring

 最近重拾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 Qtians 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 }

QT常見問題和解決方案整理