QString转换为const char*(QFileDialog得到的QString文件路径(含中文)转换为fstream可用的const char*文件路径)以及解决Qt中文字符串乱码的一种思路

    xiaoxiao2021-03-25  201

    对于不含中文的文件路径,可用如下代码解决:

    QString path=QFileDialog::getOpenFileName(this,QObject::tr("set filepath")); char* ch; QByteArray ba =path.toLatin1(); ch=ba.data(); ofstream test; test.open(ch); test<<"测试测试"; test.close();如果需要支持中文路径,则将QString::toLocal8bit()转换为QByteArray,再调用函数data()获得char*对象,代码如下:

    QString path=QFileDialog::getOpenFileName(this,QObject::tr("set filepath")); char* ch; QByteArray ba =path.toLocal8Bit(); ch=ba.data(); ofstream test; test.open(ch); test<<"测试测s试"; test.close();不过,也可以用QFile和QTextStream来替代这种方案,无需任何转换。代码如下:

    QString path=QFileDialog::getOpenFileName(this,QObject::tr("set filepath")); QFile test(path); if(test.open(QIODevice::WriteOnly)) { QTextStream te(&test); te<<QString::fromLocal8Bit("测试");//本行如果直接写te<<"测试";生成的文件打开会乱码。setCodec等函数也无法解决乱码问题。 test.close(); } else qDebug("*****open failed********");

    上面用了QString::fromLocal8bit(“测试”)来将中文转换为正确编码的QString输入到文件中。源码直接用“测试”这个字符串,转换为QString对象时会用默认的编码,不一定是源码的编码格式,所以会出现乱码。比如以下代码:

    QString path=QFileDialog::getOpenFileName(this,QObject::tr("set filepath")); QFile test(path); if(test.open(QIODevice::WriteOnly)) { QTextStream te(&test); te<<"测试";//本行如果直接写te<<"测试";生成的文件打开会乱码。setCodec等函数也无法解决乱码问题。 test.close(); } else qDebug("*****open failed********");实际上是将“测试”这个const char*对象转换为QString,转换过程中会用Qt默认的编码格式,因此会出现乱码。上面代码和以下代码等价,同样会乱码。

    QString path=QFileDialog::getOpenFileName(this,QObject::tr("set filepath")); QFile test(path); if(test.open(QIODevice::WriteOnly)) { QTextStream te(&test); QString str="测试";//等价QString str("测试") te<<str; test.close(); } else qDebug("*****open failed********");将上面代码换成:

    QString path=QFileDialog::getOpenFileName(this,QObject::tr("set filepath")); QFile test(path); if(test.open(QIODevice::WriteOnly)) { QTextStream te(&test); QString str=QString::fromLocal8Bit("测试");//等价QString str(QString::fromLocal8Bit("测试")) te<<str; test.close(); } else qDebug("*****open failed********"); 中文就显示正常了。

    从控件中得到的QString对象如果包含中文,是不需要考虑编码问题的。比如如下代码:

    QString path=QFileDialog::getOpenFileName(this,UdpSender::tr("set filepath")); QFile test(path); if(test.open(QIODevice::WriteOnly)) { QTextStream te(&test); te<<path; test.close(); } else qDebug("*****open failed********");假设文件路径path中就包含了中文字符,运行以上代码后,path路径处保存的文件里,中文路径显示是正常的。

    转载请注明原文地址: https://ju.6miu.com/read-435.html

    最新回复(0)