Archived:如何在Qt Symbian中保存文件为中文文件名
文章信息
Contents |
问题
如果在Symbian平台中使用如下代码,想将当前操作的一个图片保存
QString fileName=QFileDialog::getSaveFileName();
QPixmap *pm=new QPixmap(800,400);
pm->save(fileName);
delete pm;
如果在弹出的对话框中,利用手机输入法输入文件名时,会出现中文名无法保存的问题。将图片保存部分代码换成普通的文件处理
同样碰到中文名无法保存的问题。
分析
这种情况一般是由字符串的编码引起,Qt内部使用的编码格式是Unicode的,可能在两个地方传递的不是Unicode编码
- 文件选择框读入的字符串
- 文件保存到磁盘时的字符串
要测读入的字符串是否为Unicode只需通过,QLabel或者QPushButton的setText(fileName)函数,如能正确显示则表示读入的文件名是正常的。经测试是第二步有问题,因为Symbian本地文件名使用的是UTF-8。
解决
Qt中用于控制读入和写出文件系统时的字符编码由QTextCodec::setCodecForLocale()所决定。在symbian中,只需在程序中调用
QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
即可
code example
#include <QtGui>
class MyWidget:public QWidget{
Q_OBJECT
public:
MyWidget(QWidget *parent=0);
protected slots:
void buttonclick();
private:
QPushButton *pb;
};
MyWidget::MyWidget(QWidget *parent)
:QWidget(parent){
pb=new QPushButton(this);
QVBoxLayout *vbox=new QVBoxLayout(this);
vbox->addWidget(pb);
connect(pb,SIGNAL(clicked()),this,SLOT(buttonclick()));
}
void MyWidget::buttonclick(){
QString fileName=QFileDialog::getSaveFileName();
#if 1
QPixmap *pm=new QPixmap(800,400);
pm->save(fileName);
delete pm;
#else
QFile file;
file.setFileName(fileName);
file.open(QIODevice::WriteOnly);
file.close();
#endif
pb->setText(fileName);
}
int main(int argc,char *argv[]){
QApplication app(argc,argv);
QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
QMainWindow mw;
mw.setCentralWidget(new MyWidget(&mw));
mw.showMaximized();
return app.exec();
}
#include "main.moc"
补充
这个问题应该是Qt-4.6.2以前版本的一个bug,该bug报告在 https://bugreports.qt-project.org/browse/QTBUG-7175 上,如果是4.6.3之后版本应该没有这个问题


(no comments yet)