How to save binary file from QByteArray rather than QTextStream
-
I am working on a binary file editor (not quite a hex editor).
I started with themdi
example supplied with Qt.
I changed the opening of the file to binary.
But don't know what I'm doing to use aQByteArray
instead ofQString
.
So here is the save file function with my failed attempt indicated:bool MdiChild::saveFile(const QString &fileName) { QFile file(fileName); if (!file.open(QFile::WriteOnly)) { // was | QFile::Text)) { // ... return false; } // QTextStream out(&file); // What I had QByteArray out(&file); // What I want out << toPlainText(); setCurrentFile(fileName); return true; }
Gives error:
/home/.../mdichild.cpp:120: error: no matching function for call to 'QByteArray::QByteArray(QFile*)' QByteArray out(&file); ^
I understand that
QByteArray
is not a stream, but don't know what to do here.
Also not yet comfortable knowing what can be overloaded or modified in classes -- forQPlainTextEdit()
Thank you. -
Instead of using QByteArray as a type of 'QTextStream' you should probably do it this way:
{ QFile file(fileName); if (!file.open(QFile::WriteOnly)) { // was | QFile::Text)) { // ... return false; } // assuming you need a QByteArray() QByteArray data(this->toPlainText().toLatin1()); file.write(data); // or cut out the middle man file.write(this->toPlainText().toLatin1()); setCurrentFile(fileName); return true; }
Note: If you are looking to convert the binary file data to and from hexadecimal QByteArray has functions 'toHex()' and 'fromHex()' which work quite well.
-
Instead of using QByteArray as a type of 'QTextStream' you should probably do it this way:
{ QFile file(fileName); if (!file.open(QFile::WriteOnly)) { // was | QFile::Text)) { // ... return false; } // assuming you need a QByteArray() QByteArray data(this->toPlainText().toLatin1()); file.write(data); // or cut out the middle man file.write(this->toPlainText().toLatin1()); setCurrentFile(fileName); return true; }
Note: If you are looking to convert the binary file data to and from hexadecimal QByteArray has functions 'toHex()' and 'fromHex()' which work quite well.