最近因为项目需求,使用QT做界面,新手学习,记录一些笔记。虽然QT已经做好了标准对话框的国际化,但是有时候对于中文的翻译可能达不到我们期望的,所以就需要我们自己来修改。比如下面的代码中,利用了国际化:
// 写在main函数中
QApplication app(argc, argv);
QString translatorFileName("C:/Qt/4.8.6/translations/qt_zh_CN.qm");
QTranslator translator;
if (translator.load(translatorFileName))
{
app.installTranslator(&translator);
}
在显示treeview数据的函数中添加如下代码:
// 在treeview中显示桌面上的文件信息
QFileSystemModel* model = new QFileSystemModel();
model->setRootPath(QDesktopServices::storageLocation(QDesktopServices::DesktopLocation)); //文件夹路径可以根据需要更改
ui.treeView->setModel(model);
ui.treeView->setRootIndex(model->index(QDesktopServices::storageLocation(QDesktopServices::DesktopLocation)));
ui.treeView->setSortingEnabled(true);
运行程序,结果如下:
从上图可以看出,最后一列的翻译就不理想,此时,我们如果想修改为理想的,则可以在显示treeview数据的函数中添加如下代码(去掉main函数中的QTranslator):
// 在treeview中显示桌面上的文件信息
QFileSystemModel* model = new QFileSystemModel();
model->setRootPath(QDesktopServices::storageLocation(QDesktopServices::DesktopLocation)); //文件夹路径可以根据需要更改
ui.treeView->setModel(model);
ui.treeView->setRootIndex(model->index(QDesktopServices::storageLocation(QDesktopServices::DesktopLocation)));
ui.treeView->setSortingEnabled(true);
// 将treeview 的头部设置为中文,此段代码必须在QFileSystemModel后执行,
// 由此可以猜测,QFileSystemModel中可能也有header()->setModel()类似的动作
QStringList headerList;
QStringList headerList;
string strColumn[] = {
"名称",
"大小",
"类型",
"修改日期",
}; // 为了方便大家看,此处的字符串就出现在代码里了,
// 一般情况下,字符串还是不要出现在代码中(不然不利于资源分离)
for (int i = 0; i < sizeof(strColumn)/sizeof(strColumn[0]); ++i)
{
headerList.append(GBK::ToUnicode(strColumn[i])); //GBK是字符串转换类,可以自己封装
}
QStandardItemModel* itemModel = new QStandardItemModel();
itemModel->setHorizontalHeaderLabels(headerList);
ui.treeView->header()->setModel(itemModel); //修改header的方法有很多,我只是取了其中一种
运行程序,结果如下:
以上实现了需要的功能,性能方面,未做考究(在Windows平台上,用QT实现界面虽然强大,但是性能上还是比不上MFC的,两者各有千秋吧)。