2011-04-09 70 views
0

我是编程新手。我正在创建一个小字混杂游戏来练习qt编程。在这个应用程序中,我创建了一个文本文件(score.txt)来保持玩家的分数。我已经通过:在安装目录中创建文本文件(Qt应用程序)时出现问题(使用CMake安装)

QFile scoreFile("score.txt"); 
    if (QFile::exists("score.txt")) 
    { 
     scoreFile.open(QIODevice::ReadWrite | QIODevice::Text) 
     // and update the score. 
    } 
    else 
    { 
     scoreFile.open(QIODevice::ReadWrite | QIODevice::Text);//create score file 
     //and write the score to it. 
    } 

此代码在这里工作良好。现在,我使用CMake的构建和安装使用此代码生成的二进制(我工作在Ubuntu):

#set project name, version and build code here. 

安装(靶向wordJumbleGame目标纸)

我在建项目的/ home/MYNAME /项目/建设/

我的源代码是在/ home/MYNAME /项目/ src目录/

的CMakeLists.txt是/home/myname/project/CMakeLists.txt

我使用make install安装了程序。 直到这里所有的东西都正常工作。但现在的问题是,当我运行这个程序(我从终端运行命令wordJumbleGame运行它)它在/ home/myname/project/build目录中创建score.txt。它不是在安装目录bin中创建的。

所以请帮助我,我做错了什么。还请告诉我如何让我的程序出现在应用程序 - >游戏列表中,以便我可以从那里运行它而不是从命令提示符处运行。

回答

1

除非在斜线(在unix上)或驱动器路径(Windows)上加前缀,否则QFile的构造函数参数是相对于当前工作目录的相对路径。 score.txt是在build /目录下创建的,因为这可能是你执行二进制文件的地方。

您不能将score.txt存储在/ usr/bin目录中,因为通常情况下,您不能在没有root权限的情况下写入score.txt。

你想要做的是获得一个目录的路径,你可以存储你的score.txt文件。为此,您可以使用QDesktopServices类。这将为您提供每个用户的目录信息。这里有一个例子:

#include <QDesktopServices> 

// this would go in main(), probably 
QCoreApplication::setApplicationName("word jumble game"); 

// now when you want to read/write the scores file: 
QString dataPath = QDesktopService::storageLocation(QDesktopService::DataLocation); 
QFile scoreFile(dataPath + "score.txt"); 

// on my system, this produces: "/home/adam/.local/share/data/word jumble game/score.txt" 
// it will produce something similar for Windows and Mac too 

你应该获得路径信息,以保持用户数据目录漂亮和组织之前通过QCoreApplication::setApplicationName设置你的名字器件的应用。

至于让您的应用程序在游戏列表中,您需要创建一个遵循freedesktop.org规范的菜单条目。 我帮不了你,但 this是一个很好的起点。其他人可能会为你提供更多信息。

您需要创建一个.desktop条目文件并使用xdg-desktop-menu install进行安装。这里有两个资源给你:freedesktop.org menu specadding .desktop files using CMake

+0

感谢Adam帮助。 – UNK 2011-04-09 12:46:18

相关问题