Qt GUI open a file using push button - c++

I need to create qt gui push button with line edit, where I press the button which leads to browsing a folder to find a textfile I want to import. The textfile will be parsed afterwards. I would prefer to use combobox but I have no idea how to browse the folder through gui. Perhaps something like QDir related stuff should work but please help.
Basically, I want to import/open a textfile using push button/combobox.

What you are looking for is QFileDialog
connect the clicked() signal of your QPushButton to a slot that performs:
QString fileName = QFileDialog::getOpenFileName(this,
tr("Open Text file"), "", tr("Text Files (*.txt)"));
Then you can parse the file using for instance QFile and QTextStream:
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
QTextStream in(&file);
while (!in.atEnd())
{
QString line = in.readLine();
process_line(line);
}
EDIT
If you want to parse a file where each line contains 31 floats that you want to store in a float data[31], I would first create the class:
struct FloatLine { float data[31]; };
Then store all the lines in a QList<FloatLine>, this way:
QList<FloatLine> floatLines;
QTextStream in(&file);
while (!in.atEnd())
{
QString line = in.readLine();
QTextStream lineStream(&line);
floatLines << FloatLine();
for(int i=0; i<31; i++)
lineStream >> floatLines.last().data[i];
}

You might want to use QFileDialog, there are few example at that QtDocument.

Related

How to separate file name and file path in QT

I've got a path like "C:\Users\Rick\html.txt". So how can I separate the file path and filename? My main aim is to extract the file path and obtain "C:\Users\Rick" for a text editor app. I'm receiving the path as a QString from QFileDialog::getSaveFileName(). So I want to use that path as the window title and next path if the user tries to open a file
if(!checkTextField()){
QMessageBox::StandardButton reply = QMessageBox::question(this,this->appName,this->document_modified);
if(reply == QMessageBox::Yes){
QString filename = QFileDialog::getSaveFileName(this,"Save the File",QDir::homePath(),this->textFilter);
QFile file(filename);
if(!file.open(QIODevice::ReadWrite | QIODevice::Text))
return;
QTextStream out(&file);
QString text = ui->textEdit->toPlainText();
out << text;
file.flush();
file.close();
}
}```
You should look in to QFileInfo
QFileInfo info("c:/my/path/to/dir/file.txt");
info1.absoluteFilePath(); // returns "c:/my/path/to/dir/file.txt"
info1.dir(); // returns "c:/my/path/to/dir"
info1.filename(); // returns "file.txt"

how to read only one line in a text file which has particular word using Qt

I am reading a .txt file, I want to read only 1 line with particular word. I'm using Qt Creator.
How can I achieve this?
This is my code so far:
QFile file("/home/a1.txt");
if (!file.open(QFile::ReadOnly | QFile::Text)) {
QMessageBox::warning(this,"title","file not open");
}
QTextStream in(&file);
QString text = in.readAll();
ui->plainTextEdit->setPlainText(text);
file.close();
If you want to search all lines for a specific word you can do this
QFile file("/home/a1.txt");
if (!file.open(QFile::ReadOnly | QFile::Text)) {
QMessageBox::warning(this,"title","file not open");
}
QTextStream in(&file);
QString text;
while (!in.atEnd()) {
text = in.readLine();
if (text.contains(/*Search her for the word you want.*/))
break;
}
ui->plainTextEdit->setPlainText(text);
file.close();
So you loop through all lines. And in every line you check if the word exist. If yes you can stop searching and leave the loop.
I hope this helps!

Open a file specified in a QLabel

I want to put in a label the direction of the file then click a button and open it in another label :
QFile file("/Users/Ignacio/Documents/3 curso/segundo semestre/cafeteria-2/txt/HEREGOESTHEFILE.txt");
if(!file.open(QIODevice::ReadOnly))
QMessageBox::information(0,"info",file.errorString());
QTextStream in (&file);
ui->cajagrande->setText(in.readAll());
So I tried something like this
Char a [] = ui->label->text();
QFile file(a);
if(!file.open(QIODevice::ReadOnly))
QMessageBox::information(0,"info",file.errorString());
QTextStream in (&file);
ui->cajagrande->setText(in.readAll());
but it dosen't work.
Thanks for the help
Be careful that you were using the file even on errors, place braces correctly as well as the else clause.
QFile file(ui->label->text());
if(!file.open(QIODevice::ReadOnly)) {
QMessageBox::information(0, "info", file.errorString());
} else {
QTextStream in(&file);
ui->cajagrande->setText(in.readAll());
}
Note: a QFile can be open directly with a filename given as QString, no need to converting to a pointer of chars.

How to set the QLineEdit with new line

Currently I am copying the text to a LineEdit and on click PushButton it will write the text to a file which is "data.txt". I have written a readfile() which will read the text from data.txt and on click PushButton it should display the text in new line format at LineEdit.
Here is my code:
void MainWindow::writefile()
{
QString str = ui->lineEdit->text();
QString filename = "data.txt";
QFile file(filename);
file.open(QIODevice::WriteOnly|QIODevice::Text);
QTextStream out(&file);
out<<str<<endl;
file.close();
}
void MainWindow::readfile()
{
QString filename = "data.txt";
QFile file(filename);
file.open(QIODevice::ReadOnly|QIODevice::Text);
QTextStream in(&file);
QString str = in.readLine();
ui->lineEdit_2->setText(str);
file.close();
}
void MainWindow::on_pushButton_2_clicked()
{
readfile();
}
void MainWindow::on_pushButton_clicked()
{
writefile();
}
Please suggest how to separate those comma-separated strings and must display in new line format
The documentation of QLineEdit says:
A line edit allows the user to enter and edit a single line of plain text [...]
A related class is QTextEdit which allows multi-line, rich text editing.
Thus, you should use the QTextEdit widget instead of QLineEdit to allow multi-line text. It also has a setText, so you can use it the same way.
To replace commas with new line characters use the replace method:
// ...
QString str = in.readLine();
str = str.replace(",", "\n");
ui->textEdit_2->setText(str);
//...

Qt QTextEdit loading just half text file

I have a problem: my project is a very simple one with a QTextEdit and a QSyntaxHighlighter, I'm trying to load a .cpp file and highlighting just the eighth line of that file, but the QTextEdit can't load the entire file if I ask it to highlight the line.
The following image shows the problem:
The relevant code of the application is the following:
void MainWindow::openFile(const QString &path)
{
QString fileName = path;
if (fileName.isNull())
fileName = QFileDialog::getOpenFileName(this,
tr("Open File"), "", "C++ Files (*.cpp *.h)");
if (!fileName.isEmpty()) {
QFile file(fileName);
if (file.open(QFile::ReadOnly | QFile::Text))
editor->setPlainText(file.readAll());
QVector<quint32> test;
test.append(8); // I want the eighth line to be highlighted
editor->highlightLines(test);
}
}
and
#include "texteditwidget.h"
TextEditWidget::TextEditWidget(QWidget *parent) :
QTextEdit(parent)
{
setAcceptRichText(false);
setLineWrapMode(QTextEdit::NoWrap);
}
// Called to highlight lines of code
void TextEditWidget::highlightLines(QVector<quint32> linesNumbers)
{
// Highlight just the first element
this->setFocus();
QTextCursor cursor = this->textCursor();
cursor.setPosition(0);
cursor.movePosition(QTextCursor::Down, QTextCursor::MoveAnchor, linesNumbers[0]);
this->setTextCursor(cursor);
QTextBlock block = document()->findBlockByNumber(linesNumbers[0]);
QTextBlockFormat blkfmt = block.blockFormat();
// Select it
blkfmt.setBackground(Qt::yellow);
this->textCursor().mergeBlockFormat(blkfmt);
}
However if you want to test the project with the cpp file I used (in the directory FileToOpen\diagramwidget.cpp), here's the complete source
http://idsg01.altervista.org/QTextEditProblem.zip
I've been trying to solve this for a lot of time and I'm starting to wonder if this isn't a bug or something similar
The QTextEdit can't accept such a big amount of text at one piece. Split it, for example like this:
if (!fileName.isEmpty()) {
QFile file(fileName);
if (file.open(QFile::ReadOnly | QFile::Text))
{
QByteArray a = file.readAll();
QString s = a.mid(0, 3000);//note that I split the array into pieces of 3000 symbols.
//you will need to split the whole text like this.
QString s1 = a.mid(3000,3000);
editor->setPlainText(s);
editor->append(s1);
}
It seems that the QTextEdit control needs time after each loading, setting a QApplication:processEvents(); after setPlainText() solves the problem although it's not an elegant solution.