Inline
Inline

Reputation: 2863

Qt: How to open file by external programm, "open with..." dialog

How can I open a file by associated, external program and if it fails call a "open with..." dialog?

Can it be platform independent code? Or I need to use

#ifdef
#else 
#endif 

constructions to implement "open with..." dialog call for every platform?

Thanks in advance

EDIT: Update, after few hours of researching, i found good solution for Windows.

We try to open file with ShellExecute(...), if it fails with file association error, we open file by "open as" Shell32.dll dialog

QString file_path = "C:\VeryGoodPath.txt";
int iResult = (int)ShellExecuteA(0, 0, file_path.toStdString().c_str(), 0, 0 , SW_SHOW );
if(iResult>32)
{
    // Succesful run
}
else
{
    if(SE_ERR_ASSOCINCOMPLETE==iResult)
    {
        QString ShellCmd = "C:\\Windows\\system32\\shell32.dll,OpenAs_RunDLL \""+file_path +"\"";
        ShellExecuteA(0,"open", "C:\\Windows\\system32\\rundll32.exe",ShellCmd.toStdString().c_str(),NULL, SW_NORMAL);
    }
    else
    {
        // Errors
    }
}

EDIT2: Problem was, that i dont use in

 QDesktopServices::openUrl(...)

this function

 QUrl::fromLocalFile("<path_to_your_file>")

Upvotes: 1

Views: 2361

Answers (1)

Felix
Felix

Reputation: 7146

One easy way is to use QDesktopServices::openUrl:

QDesktopServices::openUrl(QUrl::fromLocalFile("<path_to_your_file>"));

This way you can let the operating system handle it. If a program is associated with that file (or URL in general. You can use this function to open an url in the default browser, too) the operating system will launch it or show the default "Open with" dialog.

Upvotes: 5

Related Questions