Open txt file with default program

2019-08-31 06:26发布

问题:

In my program, I have a button that I want to open a text file in a relative directory. I'm using QDesktopServices like this:

QDesktopServices::openUrl(QUrl::fromLocalFile("file:///stuff/block_settings.txt"));

When the button is pressed, nothing happens.

The file is in a folder named "stuff" that resides in the same location as my .exe. It is the same directory used for all my other tasks.

What am I doing wrong?

Thanks.

回答1:

The file is in a folder named "stuff" that resides in the same location as my .exe. It is the same directory used for all my other tasks. What am I doing wrong?

Seems like your full path is an overcomplication. I would suggest to use this intead:

QString QCoreApplication::applicationDirPath() [static]

Returns the directory that contains the application executable.

For example, if you have installed Qt in the C:\Qt directory, and you run the regexp example, this function will return "C:/Qt/examples/tools/regexp".

On Mac OS X this will point to the directory actually containing the executable, which may be inside of an application bundle (if the application is bundled).

Warning: On Linux, this function will try to get the path from the /proc file system. If that fails, it assumes that argv[0] contains the absolute file name of the executable. The function also assumes that the current directory has not been changed by the application.

So, you would be writing this code:

QDesktopServices::openUrl(QString("%1/stuff/block_settings.txt")
                          .arg(QCoreApplication::applicationDirPath()));


回答2:

I fixed the issue. Changed to:

QDesktopServices::openUrl(QUrl("file:stuff\\block_settings.txt"));

Not sure how that works because I don't see that configuration on any tutorial anywhere but w/e