如何在Qt Symbian中保存文件为中文文件名

问题

如果在Symbian平台中使用如下代码,想将当前操作的一个图片保存

QString fileName=QFileDialog::getSaveFileName();
QPixmap *pm=new QPixmap(800,400);
pm->save(fileName);
delete pm;

如果在弹出的对话框中,利用手机输入法输入文件名时,会出现中文名无法保存的问题。将图片保存部分代码换成普通的文件处理

QFile file;
file.setFileName(fileName);
file.open(QIODevice::WriteOnly);
file.close();

同样碰到中文名无法保存的问题。

分析

这种情况一般是由字符串的编码引起,Qt内部使用的编码格式是Unicode的,可能在两个地方传递的不是Unicode编码

  • 文件选择框读入的字符串
  • 文件保存到磁盘时的字符串

要测读入的字符串是否为Unicode只需通过,QLabel或者QPushButton的setText(fileName)函数,如能正确显示 则表示读入的文件名是正常的。经测试是第二步有问题,因为Symbian本地文件名使用的是UTF-8。

解决

Qt中用于控制读入和写出文件系统时的字符编码由QTextCodec::setCodecForLocale()所决定。在symbian中,只 需在程序中调用

QTextCodec::setCodecForLocale(QTextCodec::codecForName(“UTF-8″));

即可

code example

#include

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”

Tags: , , ,
This entry was posted on Tuesday, March 30th, 2010 at 1:22 PM and is filed under Qt技术, s60. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

4 Responses to “如何在Qt Symbian中保存文件为中文文件名”

  1. 臭虫 says:

    qiliang:多谢,我想也应该是系统去做这个事情,不用应用来干涉.

  2. 喃喃 says:

    您好,大牛,想请教你一个问题,qt在symbian上,显示汉字只能生成qm文件发布吗,我y用tr()标记都没效果

  3. 喃喃 says:

    我的问题解决了,我用的港水,这样设置tr()标记,居然好了, QTextCodec::setCodecForTr(QTextCodec::codecForName(“GBK”));

Leave a Reply