Open txt file with default program

痴心易碎 提交于 2019-12-12 01:29:39

问题


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



来源:https://stackoverflow.com/questions/21083277/open-txt-file-with-default-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!