reading a file into Qt - c++

I wrote a Program in Qt 5.2.1 that writes some data into a file and now I want to read it and display it. ( in a text edit or any other widget)
Here is my code ( the part I thought is relevant ) -
But i don't get the desires result ... could you look into it and tell me what i an doing wrong
void MainWindow::on_Search_clicked()
{
QString name ;
name = ui->Search_name->text();
QFile readfile("data.txt");
if(!readfile.open(QIODevice::ReadOnly))
{
qDebug() << "error opening file: " << readfile.error();
return;
}
QTextStream instream(&readfile);
QString line = instream.readLine();
// ui->text is a QPlainTextEdit*
ui->text->insertPlainText(line);
readfile.close();
return;
}

You should use
void QPlainTextEdit::appendPlainText ( const QString & text ) [slot]
method, link.

Related

How do you delete a sub-string in a string(qstring) in Qt

Is there a function in Qt similar to delete() and copy() in Delphi.
I am reading data from a device connected to my computer via USB and storing it as a QString. Every line that is read is not the same (or is cut short, even while using readyRead). I created a buffer sting to add these "half sting" (eg. string = "This" instead of "This is a string#") to and now I want to copy the string up until the '#' and then delete the string so if new "half stings" get added I can do the same with them. The code below is what I tried
void MainWindow::readSerial()
{
QByteArray serialData = port->readAll();
serialBuffer += serialData;
QByteArray serialString = serialBuffer.
qDebug() << serialString;
ui -> textEdit ->append(serialString);
//serialBuffer.replace(serialString,"");
}
The above code only returns an empty string.
void MainWindow::readSerial()
{
QByteArray serialData = port->readAll();
serialBuffer += serialData;
QString serialString = serialBuffer.mid(serialBuffer.indexOf("$"),serialBuffer.indexOf("\r\n"));
qDebug()<< "index of \r\n" << serialBuffer.indexOf("\r\n");
qDebug() << "SerialString" <<serialString;
ui -> textEdit ->append(serialString);
qDebug() << "SerialBuffer: " << serialBuffer;
serialBuffer.replace(serialString + "\r\n","");
}
the above code works. Thanks all.
regards

QstringList to Qstring conversion issues

I am working on VS2015 with qt framework. In my source code, I have a function for printing in the GUI screen.
This function is called each time something needs to be printed.
It goes like this.
void Trial::Print_MessageBox(QString string)
{
ui.MessagesScreen->appendPlainText(string);
Cursor_Messagebox.movePosition(QTextCursor::End);
ui.MessagesScreen->setTextCursor(Cursor_Messagebox);
ui.MessagesScreen->ensureCursorVisible();
}
// Output in MessageBox
void Trial::Print_MessageBox(QFlags<QNetworkInterface::InterfaceFlag> flags)
{
QString str = QString("Flag %1").arg(flags);
ui.MessagesScreen->appendPlainText(str);
}
The above function has no problems and running well.
Now I am trying to read a text file. This has set of values in no order or size. An example for this:
231, 54, 4 \n
47777, 2211, 676, 9790, 34236, 7898\n
1, 3\n
Objective is to convert these into integers (line by line) and print them in the GUI and also send them (line by line) to other system. So I tried to do it with the following.
void Trial::ReadFile_Data()
{
QFile file("input.txt");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
Print_MessageBox("Error in reading File");
return;
}
QTextStream in(&file);
while (!in.atEnd())
{
QString line = in.readLine();
Print_MessageBox(line);
int conv = line.toInt();
QString str = QString("%1 %2").arg("Values are: ").arg(conv);
Print_MessageBox(str);
QStringList fields = line.split(",");
}
file.close();
}
When I print the "line", it is just printing the same values as in the file. When I do the conversion and printing, I get an error (which is expected) Now I try to remove "," with the help of split then I get QstringList which I cannot use as I have the Qstring function to print(this cant be changed)
I am not getting any pointers from here. Please help me out as this is bugging me since long time.
Just simple...
QStringList::const_iterator constIterator;
for (constIterator = fonts.constBegin(); constIterator != fonts.constEnd();
++constIterator) {
cout << (*constIterator).toLocal8Bit().constData() << endl;
}
where fonts is your QStringlist
Your question reduces to "How do I iterate over a QStringList".
Like this:
// C++11
for (auto field : fields) Print_messageBox(field);
// C++98
foreach (QString field, fields) Print_messageBox(field);
See here for information about how foreach a.k.a Q_FOREACH was implemented.

change the name file putting the first line of my file C++ & Qt

I want to change the name of my file but I don't know how to do it. I have a .txt with words in two lines,and like to take the first line same as name of my file .txt.
This is my code:
void ventana1::on_ButtonGuardar_clicked()
{
QDir directory("C:/Users/Jaime/Desktop/interfaz/pacientes");
QString mFilename = directory.filePath("paciente.txt");
QFile sFile(mFilename);
if(sFile.open(QFile::WriteOnly | QFile::Text))
{
QTextStream out(&sFile);
out << ui.lineEdit_2->text()<< "\n"
<< ui.lineEdit->text();
sFile.flush();
sFile.close();
}
}
Simply replace
QString mFilename = directory.filePath("paciente.txt");
by
QString mFilename = directory.filePath(ui.lineEdit_2->text());
if you need to have the content of your lineEdit as your filename.

Creating an Efficient Function

I am a beginner in my fourth week learning C++; I had been working on CodeBlocks, but due to my interest in making GUIs I switched to Qt Creator. Back in CodeBlocks I had created a function that would avoid all the repetition in the code below, only changing the "TXT FILE". However, with Qt Creator's "specialized" C++ I am having trouble making sense of how to create a function to avoid all this repetition.
Any ideas? (I'm too far into this Qt project to go back to CodeBlocks.)
The "TXT FILE" changes depending on which RadioButton the user selects.
void MovierRec::on_searchButton_clicked()
{
int randomValue = qrand() % 100;
QList<QString> titles;
if(ui->modernButton->isChecked())
{
QFile myfile(":/classics.txt");
if (myfile.open(QIODevice::ReadOnly))
{
QTextStream in(&myfile);
while (!in.atEnd())
{
QString line = in.readLine();
titles.append(line);
}
myfile.close();
ui->textBrowser->setPlainText (titles[randomValue]);
}
}
else if(ui->romanceButton->isChecked())
{
QFile myfile(":/romance.txt");
if (myfile.open(QIODevice::ReadOnly))
{
QTextStream in(&myfile);
while (!in.atEnd())
{
QString line = in.readLine();
titles.append(line);
}
myfile.close();
ui->textBrowser->setPlainText (titles[randomValue]);
}
}
else if(ui->scifiButton->isChecked())
{
QFile myfile(":/scifi.txt");
if (myfile.open(QIODevice::ReadOnly))
{
QTextStream in(&myfile);
while (!in.atEnd())
{
QString line = in.readLine();
//titles.append(line);
}
myfile.close();
ui->textBrowser->setPlainText (titles[randomValue]);
}
}
This is generic programming issue, could refactor code in a better way:
// I didn't dig into every line of the code. just provide the refactor idea here
void getTitle(const QString& file_name, QList<QString>& titles;)
{
QFile myfile(file_name);
if (myfile.open(QIODevice::ReadOnly))
{
QTextStream in(&myfile);
while (!in.atEnd())
{
QString line = in.readLine();
titles.append(line);
}
myfile.close();
}
}
void MovierRec::on_searchButton_clicked()
{
int randomValue = qrand() % 100;
QList<QString> titles;
if(ui->modernButton->isChecked())
{
getTitle("classics.txt", titles);
}
else if(ui->romanceButton->isChecked())
{
getTitle("romance.txt", titles);
}
else if(ui->scifiButton->isChecked())
{
getTitle("scifi.txt", titles);
}
ui->textBrowser->setPlainText(titles[randomValue]); // move the dup action to the end
}
QT is well known for Signals and Slots. Each button can be connected to a slot. For Example in your case. You can connect each radio button to a slot. in order to do that, Open ur GUI form, right click on the radio button and select "Go To Slot", and select the slot you want to connect to.
This will create an empty function in ur .cpp file.
Now write your code for that button. And this function is called only when that particular Button is pressed/clicked .
example:
void ClassA::on_radioButton_clicked()
{
// write your code inside this function for , when this button is checked
}
I hope this will help you solve your issue. If you have other query , please provide more information.

Qt C++ writing data in a file , unexpected output

I have a task to save a file to computer. So this is my problem, when i write to file , it writes hex values.. I have no clue, what's wrong with my code. Here it is:
void MainWindow::on_actionSave_triggered()
{
QString filename = QFileDialog::getSaveFileName(
this,
tr("Save Document"),
QDir::currentPath(),
tr("Documents (*.txt)") );
QFile f( filename );
f.open( QIODevice::WriteOnly | QIODevice::Text );
QTextStream out(&f);
out << ui->textEdit->document();
}
QTextEdit's document method return QTextDocument, I think you want to use toPlainText method instead.
QTextEdit::document() will return a QTextDocument* which will be an Hex value (address). That's what you are adding in the file.
To get the contents from the QTextEdit use QString QTextEdit::toPlainText ()
HTH..