Using file system in Qt C++ - c++

I have created a basic UI in Qt with lots of text fields, now i want to use the text or number that the user enters and store it in a file ( preferably a SQL db file, but a text file will do just fine).
after saving the file I should be able to access that info again such that it lays out everything in a tabular format.

See QTextStream class:
QFile data("output.txt");
if (data.open(QFile::WriteOnly | QFile::Truncate)) {
QTextStream out(&data);
out << yourLabel->text();
}
You can read your data in similar way.

Related

How to specify which types of files you can open

I am currently starting to develop a QT desktop application, to edit the scripting language "Lua". The implementation should be pretty basic, opening Lua extension files, saving and editing them. The problem that i have stumbled upon is that I want to be able to open/save/edit just Lua files. While reading a QT documentation i stumbled upon an explanation of how you can open files for a so called "notepad" editor. They have provided the following example code:
QString fileName = QFileDialog::getOpenFileName(this, "Open the file");
QFile file(fileName);
currentFile = fileName;
if (!file.open(QIODevice::ReadOnly | QFile::Text)) {
QMessageBox::warning(this, "Warning", "Cannot open file: " + file.errorString());
return;
}
setWindowTitle(fileName);
QTextStream in(&file);
QString text = in.readAll();
ui->textEdit->setText(text);
file.close();
So here they basically add a condition where the file was unable to open, (it was in this line of code if (!file.open(QIODevice::ReadOnly | QFile::Text))) but they don't specify what the condition should look like if I only want to be able to open certain types of files (in my case, lua files). The same goes for the "save" option that they have displayed.. So my question is, how should I extend this condition, to check if the files has the given extension type for Lua ? Thanks in advance.
getOpenFileName can take more arguments (has default values for some of the arguments), see the documentation here.
So your code will be something like:
QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),
"", //default path here
tr("Lua files (*.lua)"));
You could try this:
void QFileDialog::setNameFilter(const QString &filter)
Sets the filter used in the file dialog to the given filter.
/* If filter contains a pair of parentheses containing one or
more filename-wildcard patterns, separated by spaces, then
only the text contained in the parentheses is used as the filter.
This means that these calls are all equivalent: */
dialog.setNameFilter("All Lua files (*.lua)");
Taken from the docs:
https://doc.qt.io/qt-5/qfiledialog.html#setNameFilter

UTF-16LE Encoding woes with Qt text editor written in C++

So I have a QT text editor that I have started creating. I started with this http://doc.qt.io/archives/qt-5.7/gettingstartedqt.html and i have added on to it. So far I have added a proper save/save as function (the version in the link only really has a save as function), a "find" function, and an "open new window" function. Very soon, I will add a find and replace function.
I am mainly doing this for the learning experience, but I am also going to eventually add a few more functions that will specifically help me create PLC configuration files at work. These configuration files could be in many different encodings, but most of them seem to be in UTF-16LE (according to Emacs anyway.) My text editor originally had no problem reading the UTF-16LE, but wrote in plain text, I needed to change that.
Here is the snippet from the Emacs description of the encoding system of one of these UTF16-LE files.
U -- utf-16le-with-signature-dos (alias: utf-16-le-dos)
UTF-16 (little endian, with signature (BOM)).
Type: utf-16
EOL type: CRLF
This coding system encodes the following charsets:
unicode
And here is an example of the code that I am using to encode the text in my QT text editor.
First... This is similar to the link that I gave earlier. The only difference here is that "saveFile" is a global variable that I created to perform a simple "Save" function instead of a "Save As" function. This saves the text as plain text and works like a charm.
void findreplace::on_actionSave_triggered()
{
if (!saveFile.isEmpty())
{
QFile file(saveFile);
if (!file.open(QIODevice::WriteOnly))
{
// error message
}
else
{
QTextStream stream(&file);
stream << ui->textEdit->toPlainText();
stream.flush();
file.close();
}
}
}
Below is my newer version which attempts to save the code in "UTF-16LE." My text editor can read the text just fine after saving it with this, but Emacs will not read it at all. This to me says that the configuration file will probably not be readable by the programs that read it. Something changed, not sure what.
void findreplace::on_actionSave_triggered()
{
if (!saveFile.isEmpty())
{
QFile file(saveFile);
if (!file.open(QIODevice::WriteOnly))
{
// error message
}
else
{
QTextStream stream(&file);
stream << ui->textEdit->toPlainText();
stream.setCodec("UTF-16LE");
QString stream3 = stream.readAll();
//QString stream2 = stream3.setUnicode();
//QTextCodec *codec = QTextCodec::codecForName("UTF-16LE");
//QByteArray stream2 = codec->fromUnicode(stream3);
//file.write(stream3);
stream.flush();
file.close();
}
}
}
The parts that are commented out I also tried, but they ended up writing the file as Asian (Chinese or Japanese) characters. Like I said my text editor, (and Notepad in Wine) can read the file just fine, but Emacs now describes the encoding as the following after saving.
= -- no-conversion (alias: binary)
Do no conversion.
When you visit a file with this coding, the file is read into a
unibyte buffer as is, thus each byte of a file is treated as a
character.
Type: raw-text (text with random binary characters)
EOL type: LF
This indicates to me that something is not right in the file. Eventually this text editor will be used to create multiple text files at once and modify their contents via user input. It would be great if I could get this encoding right.
Thanks to the kind fellows that commented on my post here, I was able to answer my own question. This code here solved my problem.
void findreplace::on_actionSave_triggered()
{
if (!saveFile.isEmpty())
{
QFile file(saveFile);
if (!file.open(QIODevice::WriteOnly))
{
// error message
}
else
{
QTextStream stream(&file);
stream.setCodec("UTF-16LE");
stream.setGenerateByteOrderMark(true);
stream << ui->textEdit->toPlainText();
stream.flush();
file.close();
}
}
}
I set the codec of the stream, and then set the the generate BOM to "True." I guess that I have more to learn about encodings. I thought that the byte order mark had to be set to a specific value or something.I wasn't aware that I just had to set this value to "True" and that it would take care of itself. Emacs can now read the files that are generated by saving a document with this code, and the encoding documentation from Emacs is the same. I will eventually add options for the user to pick which encoding they need while saving. Glad that I was able to learn something here.

QT Parsing contents of CSV file and storing into array of structures

I am creating a function named getExcelFile() to get the contents of the excel file and store it into an array of structures. First I wanted read one line of the csv file and use the delimiter , . Then I want to add the contents to the QStringList and use a for loop to iterate through an array of structures and add the contents into it. Everything is working fine except for the line where it says datalist.append((line.split(','))); Help would be greatly appreciated!
void Widget::getExcelFile(){
//Name of the Qfile object.
//filename is the directory of the file once it has been selected in prompt
QFile thefile(filename);
//QStringList named datalist.
QStringList datalist;
//If the file is successfully open
if (thefile.open(QIODevice::ReadOnly | QIODevice::Text)){
qDebug() << "File opened successfully";
while (!thefile.atEnd()){
QByteArray line = thefile.readLine();
datalist.append((line.split(',')));
}
}
qDebug() << datalist;
ui->textEdit->setPlainText(fileContent);
}
CSV files are a bit trickier to read than that.
Your specific file may have simple records, but Excel will create CSVs wth escapes, missing values, and so on.
If you take my CSV parser, you can then query it both for CSV file structure (what columns are in there and what is their type) and for the values. The parser doesn't do anything terribly complicated, but it handles the messiness of allocating memory and breaking the fields out and assigning them to columns.
If you are filling in a simple C structure, you then throw out any CSV objects that don't match. If an object does match, it's a simple loop through with calls to getfield. You then destroy the CSV object.
http://www.malcolmmclean.site11.com/www/CSVtoC/csvtoc.html

How to make a QByteArray from a Database file

Using QByteArray QIODevice::readAll() from QT5, I was able to make a bytes array from a txt file or an image, used decode after and recreated the file correctly. But, when I tried with a .db file (SQLITE) it didn't work.
I noticed that when you open a .db with a text editor, you will see "SQLite format 3" followed by encoded characters. After making a QByteArray from a .db file, followed by decode() to recreate the file, when I opened it with a text editor, the file only contains the text "SQLite format 3".
Does QByteArray only work with txt file or Image file?
If it does, how can I make a Array of bytes from a .db (SQLITE) file.
Thanks
Update1 (The code belows works):
QFile file("C:/database.db");
if(!file.open(QIODevice::ReadOnly))
qDebug()<<"You are stupid!";
QByteArray byteArray = file.readAll();
QFile file2("C:/database2.db");
file2.open(QIODevice::WriteOnly);
file2.write(byteArray);
file2.close();
file.close();
Update2:
About the decode I mentioned in my initial question, I was using the following:
QString QFile::decodeName(const QByteArray & localFileName)
which make no sense when you read carefully the documentation and was just wrong. :)
You should not open that file with QIODevice::Text flag.
Check this http://doc.qt.io/qt-5/qiodevice.html#OpenModeFlag-enum

C++ Qt cannot read the whole text file

I'm writing a tool for private use. The problem is that Qt cannot read a text file containing all contents published here.
It only reads this
The three points were pasted by Qt.
My code for reading the file is following
QFile file;
file.setFileName(m_filename);
if (!file.open(QIODevice::ReadOnly))
return;
QTextStream in(&file);
while (!in.atEnd()) {
m_fileContents += in.readLine();
}
file.close();
Do you have any idea why it doesn't work?
QFile file;
file.setFileName(m_filename);
if (!file.open(QIODevice::ReadOnly))
return;
m_fileContents = file.readAll();
I just tested your code on my own computer with your data and it works well.
If you're using an IDE, maybe it does not display all the text of your final string and this is why you have three dot at the end of your sample.
Also as evilruff suggest you can use QFile::readAll method directly.