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();
}
:/images/scores.txtis 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.