Qt选择现有文件

Qt select existing file

本文关键字:文件 选择 Qt      更新时间:2023-10-16

我是Qt的新手,我希望能够选择一个已经存在的名为default.ini的文件,该文件与exe在同一目录下。我已经有一些代码允许我这样做,但用户必须每次手动选择文件。

 QString file = QFileDialog::getOpenFileName(this, tr("Open File"), "/debug", tr("default (*.ini)"));
  if (file != NULL) {
    try {
      controller_->ConfigurationFileSave(file.toStdString());
        } catch (std::exception &e) {
      Logger::Log(std::string("Failed to save configuration: ") + e.what(), 
      Logger::kError);
    }
  }  

程序做了我想要它做的所有事情,就写/读文件而言,我只是不希望程序在打开文件时需要任何用户输入。我明白,我有用户输入的原因是因为我正在使用QFileDialog类,我只是想知道是否有另一个类自动执行它。由于

编辑1根据Arun的建议,我尝试使用Qfile。程序现在成功地从default.ini配置文件中读取,但它不会保存到配置文件中。有没有简便的方法写入文件?

 QFile file("default.ini");
 if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
 return;
 QString content = file.readAll();
 file.close();
 if (content != NULL) {
   try {
  controller_->ConfigurationFileSave(content.toStdString());
  } catch (std::exception &e) {
  Logger::Log(std::string("Failed to save configuration: ") + e.what(), 
      Logger::kError);
    }
  }

编辑2根据Arun的第二个建议:

QFile file("default.ini");
file.open(QIODevice::ReadOnly | QIODevice::Text); 
QString line = file.readAll();
file.close();
file.open(QIODevice::WriteOnly | QIODevice::Text);
try {
  controller_->ConfigurationFileSave(line.toStdString());
} catch (std::exception &e) {
  Logger::Log(std::string("Failed to save configuration: ") + e.what(), 
      Logger::kError);
}
file.close();

您的文件选择器代码正在向ConfigurationFileSave()传递文件名。下面是无需交互即可获取文件名的代码:

QDir appDir(QCoreApplication::applicationDirPath());
QFileInfo file(appDir, "default.ini");
// file.filePath() or file.absoluteFilePath() here:
controller_->ConfigurationFileSave( ___HERE___ );

您可以在QtCreator中创建一个新的控制台应用程序并将其用作main.c:

#include <QCoreApplication>
#include <QDebug>
#include <QFileInfo>
#include <QDir>
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QDir appDir(QCoreApplication::applicationDirPath());
    QFileInfo file(appDir, "default.ini");
    qDebug() << "        " << file.filePath();
    qDebug() << "        " << file.absoluteFilePath();
    return 0;
}
输出:

silver:qt_app_dir hchapman$ ls
Makefile            main.cpp            main.o              qt_app_dir          qt_app_dir.pro      qt_app_dir.pro.user
silver:qt_app_dir hchapman$ ./qt_app_dir
     "/Users/hchapman/Desktop/qt_app_dir/default.ini"
     "/Users/hchapman/Desktop/qt_app_dir/default.ini"
silver:qt_app_dir hchapman$ cd ..
silver:Desktop hchapman$ ./qt_app_dir/qt_app_dir
     "/Users/hchapman/Desktop/qt_app_dir/default.ini"
     "/Users/hchapman/Desktop/qt_app_dir/default.ini"
silver:Desktop hchapman$

下面是一个典型的示例,说明如何在不使用QFileDialog的情况下执行文件I/O。本例使用QFile

QFile file("default.ini");
if (!file.open(QIODevice::ReadWrite | QIODevice::Text))
    return;
while (!file.atEnd()) {
    QByteArray line = file.readLine();
    process_line(line);
}