Qt-QFile、QTextStream的使用

Qt C++

Posted by MetaNetworks on January 15, 2020
本页面总访问量

环境:Qt 5.14.0 + macOS Catalina 10.15.2

读取文件

1
2
3
4
5
6
7
8
9
10
11
12
QFile* configFile = new QFile();
configFile->setFileName(str+"/.blogPosition.cfg");
// 读取配置
bool openFlag = configFile->open(QIODevice::ReadOnly | QIODevice::Text);
if (!openFlag){
  return;
} else {
  QTextStream textStream(configFile);
  QString leastFolder = textStream.readLine();
  ui->BlogPositionEdit->setText(leastFolder);
}
configFile->close();

写入文件

1
2
3
4
5
6
7
8
9
10
11
12
QString str=QDir::homePath();
QFile* configFile = new QFile();
configFile->setFileName(str+"/.blogPosition.cfg");
// 写入配置
bool openFlag = configFile->open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate);
if (!openFlag){
  return -1;
} else {
  QTextStream textStream(configFile);
  textStream << pos;
}
configFile->close();

其中,QIODevice::Truncate为删除原内容写入,改为QIODevice::append即为追加写入