Windows-Autostart: Application directory seems to

2019-08-01 07:30发布

问题:

When my app is started from the autostart of Windows, Qt is not able to open it. The error that causes this is that QDir().absoluteFilePath("settings.cnf") returns the path C:/Windows/system32/settings.cnf even though my file is located in my working directory.

Does someone know what method I must call to get the right path?

回答1:

Using the default constructor QDir() defaults to the current working directory, which can be anything, depending from where the user or the system started the application. For a UI application, that's a path one should usually ignore completely.

To access data next to your application binary, use QCoreApplication::applicationDirPath(). This is usually used for global read-only data installed with the program.

For user-writable configuration settings and cached data, use QStandardPaths (Qt 5) or QDesktopServices::storageLocation() (Qt 4).



回答2:

There is no particular reason for the working directory of a GUI program to be defined. Since relative paths are relative to the working directory, the use of relative paths impies a well defined and meaningful working directory.

Now, you actually want to look for a file in the same directory as the executable. So the correct approach is to find the full path to the executable, strip off the file name, and append your file name. Now you have the full path to the file.

As a general rule, the working directory is only meaningful for console applications. So only use relative paths in a console application.