Mai Vo
Mai Vo

Reputation: 21

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

I currently have the filepath of the file that I want to access as a string, but I'm not sure if Qt has a feature that allows you to access that file with only the filepath.

I'm saving the filepath to an INI file and I want to take that filepath to open the json file that is a part of that path. This is what I've tried so far - the code would go into 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)));


}

I want to implement an action option, that has text of the filepath, and when clicked, opens up the file that I want to access. Is there a Qt feature that allows you to do this?

Upvotes: 0

Views: 463

Answers (1)

Tom Kim
Tom Kim

Reputation: 436

Try this:

  • To open with system default associated application:
void openFile(QString filepath) 
{   
    QDesktopServices::openUrl(QUrl::fromLocalFile( filepath ));
}
  • To open with specific application:
void openFile(QString filepath) 
{   
    // open with notepad
    QProcess::execute("notepad \""+ filepath +"\"");
}

Hope it helps you.

Upvotes: 1

Related Questions