0
votes

I am trying to implement a high score feature on a simple QT 5.5 game I am making. I can get it to read in the current high score, but if the player's score is better than the current high score, I'd like it to write the new name and high score to the same file. Currently, I'm getting the error message QIODevice::write (QFile, ":\images\scores.txt"): device not open. My scores.txt file is included in my .qrc.

Here's my code:

QFile myFile (":/images/scores.txt");
myFile.open(QIODevice::ReadOnly);
QTextStream in(&myFile);

QString qName = in.readLine();
QString qScore = in.readLine();
myFile.close();

bool ok;
if(qScore.toInt() < myScore)
{
    QInputDialog* inputDialog = new QInputDialog();
    inputDialog->setOptions(QInputDialog::NoButtons);
    qName =  inputDialog->getText(NULL ,"High Score!",
                                         "Enter Name:", QLineEdit::Normal,
                                         "Grandma", &ok);
    if (ok && !qName.isEmpty())
    {
        qDebug() << "Good Job!";
    }

    qScore = QString::number(myScore);
    string nameS, scoreS;
    nameS = qName.toStdString();
    scoreS = qScore.toStdString();
    myFile.open(QIODevice::WriteOnly);
    QTextStream out (&myFile);
    out << nameS.c_str() << endl << scoreS.c_str();
    myFile.flush();
    myFile.close();

}
1
The file :/images/scores.txt is a resource file that is compiled into your executable. As such, it can't be written to. You'll need to use an actual file on disk if you want to be able to write to it. - RA.
That worked! Thank you. - Paul M Oliva

1 Answers

1
votes

As noted, you can't write to a qrc resource file. You can write to an arbitrary file on disk but that raises the issue of where to store it. One way to handle this is with the QSettings Class.

It is very easy to use: How to Use QSettings

From the docs:

The QSettings class provides persistent platform-independent application settings.

Users normally expect an application to remember its settings (window sizes and positions, options, etc.) across sessions. This information is often stored in the system registry on Windows, and in property list files on OS X and iOS. On Unix systems, in the absence of a standard, many applications (including the KDE applications) use INI text files.

QSettings is an abstraction around these technologies, enabling you to save and restore application settings in a portable manner. It also supports custom storage formats.