Qt5對付中文真好用

來源:互聯網
上載者:User

標籤:style   blog   http   color   使用   os   io   檔案   

Qt好多C++程式員都在用,Qt4大家可能用的多,到了Qt5不熟悉的人到是很多,其中我喜歡的特性也是和Qt4大不一樣的地方就是對中文的處理。

Qt4中使用“QTextCodec::setCodecForTr(QTextCodec::codecForName("gb18030"));”類似的語句來解決問題,但是這種全域性的設定在一些情況是下是會影響其他語言的。例如軟體中存在多種語言。

Qt5中是怎麼解決中文的呢?我的理解就是QString一個類直接全部搞定。

例如想儲存中文到檔案中,再將檔案中的中文內容讀取到程式中。

一下是程式碼片段:

 1 bool MainWindow::__ReadFile(const QString &filename) 2 { 3     QFile infile(filename); 4     if (infile.open(QIODevice::ReadOnly)) 5     { 6         //textEdit->setPlainText(QString::fromLocal8Bit(infile.readAll())); 7         textEdit->setPlainText(QString::fromUtf8(infile.readAll())); 8         infile.close(); 9 10         setWindowModified(false);11         setWindowTitle(filename);12         return true;13     }14     return false;15 }
 1 bool MainWindow::__WriteFile(const QString &filename) 2 { 3     QFile outfile(filename); 4     if (outfile.open(QIODevice::WriteOnly)) 5     { 6         //outfile.write(textEdit->toPlainText().toLocal8Bit().data()); 7         outfile.write(textEdit->toPlainText().toUtf8().data()); 8         outfile.close(); 9 10         setWindowModified(false);11         setWindowTitle(filename);12         return true;13     }14     return false;15 }

 

QString::fromUtf8

QString::toUtf8

或者

QString::fromLocal8Bit
QString::toLocal8Bit

使用“一對”就可以完美解決中文輸入輸出問題。

大家可以試試。

實驗源碼:點擊這裡
 


 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.