qt 读取文件
前言
当去取文件时,发现如果文件路径是绝对路径,可以读取成功,如果是项目路径读取失败,
readQss(QString qssFile)
{
QFile file(qssFile);
// QString curPath=QDir::currentPath();//获取系统当前目录
// QFile file("E:/QtExercise/ctkUiPluginSignalGenerator/signalGeneratorUiPluginLib/qss.txt");
if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug()<<"Can't open the file!"<<endl;
}
QString strBuf;
while(!file.atEnd()) {
QByteArray line = file.readLine();
QString str(line);
strBuf += str;
qDebug()<< str;
}
file.close();
}
//调用
QString strFilePath = ":/qss.txt";
readQss(strFilePath);
原因
当使用相对路径时,QtCreator找不到相对路径文件,需要把文件加入到 resource.qrc文件,打开resource.qrc文件,加入文件节点 <file>qss.txt</file>
注意:写相对路径时,一定要 冒号!!!!
QString strFilePath = ":/qss.txt";
<RCC>
<qresource prefix="/signalGeneratorUiPluginLib/META-INF">
<file>MANIFEST.MF</file>
<file>qss.txt</file>
</qresource>
</RCC>