如何在 Qt/C++ 中仅将文件路径作为字符串访问文件

How to access a file with only the filepath as a string in Qt/C++?

本文关键字:文件 路径 访问 字符串 Qt C++      更新时间:2023-10-16

我目前有我想以字符串形式访问的文件的文件路径,但我不确定Qt是否具有允许您仅使用文件路径访问该文件的功能。

我正在将文件路径保存到 INI 文件,我想采用该文件路径来打开作为该路径一部分的 json 文件。这就是我到目前为止尝试过的 - 代码将进入 openFile((

void saveFileLocation(QString filename) 
{
    QSettings *settings = new QSettings(Ve::Widgets::SettingsWindowWidget::INI_FILE, QSettings::IniFormat);
    QDir dir;
    QString filePath = dir.filePath(filename);
    settings->setValue("projectFile", filePath);
    on_menuRecent_Files_aboutToShow(filePath);
}
void openFile(QString filepath) 
{   
    *insert code here*
}
void on_menuRecent_Files_aboutToShow(QString filePath)
{
    QAction* openAction = ui->menuRecent_Files->addAction(filePath);
    connect(openAction, SIGNAL(triggered()), this, SLOT(openFile(filePath)));

}

我想实现一个操作选项,其中包含文件路径的文本,单击时,将打开我要访问的文件。是否有Qt功能允许您执行此操作?

试试这个:

  • 要使用系统默认关联应用程序打开:
void openFile(QString filepath) 
{   
    QDesktopServices::openUrl(QUrl::fromLocalFile( filepath ));
}
  • 要使用特定应用程序打开:
void openFile(QString filepath) 
{   
    // open with notepad
    QProcess::execute("notepad ""+ filepath +""");
}

希望对您有所帮助。