QFile -- not reopening in text editor - c++

There are two slots for open & close in my gui.
When i open a file its content are shown in text editor, then i press close button changes are save to file.
But Now when i again press, open & reload the same file. Nothing is shown in text editor, blank editor.
Why file is not reloading ?
private:
Ui::MainWindow *ui;
QFile file;
QTextStream out;
QString url; // the url of the file
void MainWindow::on_actionOpen_triggered()
{
QString openfileurl = QFileDialog::getOpenFileName();
if(openfileurl.isEmpty() || openfileurl == url) return;
file.setFileName(openfileurl);
//if(file.open(QIODevice::ReadOnly|QIODevice::Text))
if(file.open(QIODevice::ReadWrite|QIODevice::Text))
{
url = openfileurl;
ui->textEdit->setPlainText(QString::fromUtf8(file.readAll()));
}
//Set file to -- Qtextstream
out.setDevice(&file);
}
void MainWindow::on_actionClose_triggered()
{
//Set file to -- Qtextstream
out << ui->textEdit->toPlainText();
file.close();
ui->textEdit->clear();
}

Try this way
void MainWindow::on_actionClose_triggered()
{
//Set file to -- Qtextstream
out << ui->textEdit->toPlainText();
file.close();
ui->textEdit->clear();
uri.clear();
}
I think you should clear uri before make this check:
if(openfileurl.isEmpty() || openfileurl == url) return;
It will blowup when openfileurl == url. And it will do it definitely sure if you didn't cleared the uri. And here you are:
reload the same file
...with the same content... so, the if statement goes true and returns that's why the code below is not executing the second time.

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"

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.

Qt: Load HTML source code to string

I have an HTML file stored locally that I have to extract text from.
Now I managed to prompt the user for the location and display the HTML file in a QTextBrowser by pressing a button. Now from what I understand the next step would be to convert to a string to be able to search for text inside the source code.
Here's my Button_clicked method so far
void MainWindow::on_getHTMLButton_clicked()
{
QString filename = openFilenameDialog();
if (filename.isEmpty())
{
QMessageBox::information(this, tr("File Name"), "Es wurde keine gültige Datei angegeben.");
}
else
{
QFile file(filename);
if (!file.open(QIODevice::ReadOnly))
{
QMessageBox::information(0, "Info", file.errorString());
}
else
{
QTextStream in(&file);
ui->textBrowserHTML->setText(in.readAll());
}
}
}
The HTML file shows in textBrowser without any issues.
My understanding so far is that I need to create a string to search for a substring in the source code.
Now my problem is that I cannot seem to create a string object with the source of the HTML file as content.
Something like
QString string = in.readAll();
does not seem to work...
I had to learn that after having read out the stream and putting it to the ui by
ui->textBrowserHTML->setText(in.readAll());
the stream is empty – so when I attempt to to do a readAllagain it results in an empty string.

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 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.