Getting a specific text from a text file and inserting to a QStringList!
-
IN my qt c++ application I have created a functionality to upload and read text files! I want to get a specific part of selected text lines to a QStringLIst!
Following is my codeMainWindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: QString filepath; void readValues(); QStringList values; explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private slots: void on_pushButton_clicked(); void on_pushButton_2_clicked(); private: Ui::MainWindow *ui; };
MainWindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include "QFileDialog" #include "QTextStream" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_clicked() { filepath=QFileDialog::getOpenFileName(this, "Get Any File"); ui->lineEdit->setText(filepath); } void MainWindow::readValues(){ QFile file(filepath); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return; QTextStream in(&file); while (!in.atEnd()) { QString line = in.readLine(); values<<line; } } ui->label->setText(QString::number(values.size())); } void MainWindow::on_pushButton_2_clicked() { readValues(); }
The text file(names.txt) I read have the following format!
<h>Hello<h>
<name>John</name>
<h>Hello<h>
<name>Smith</name>
<h>Hello<h>
<name>Mary</name>
<h>Hello<h>
<name>Anne</name>
<h>Hello<h>
<name>Jennifer</name>
<h>Hello<h>Currenly I get all the text lines into the QStringList!
I want to get the words(without <name></name> tags) John,Smith,Marry,Anne,Jennifer into the QStringList named values! How can I do it? -
void MainWindow::readValues(){ QFile file(filepath); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return; const QRegularExpression nameExp(R"***(<name>(.+)<\/name>)***"); QTextStream in(&file); QString line; while (stream.readLineInto(&line)) { const auto nameMatch = nameExp.match(line); if(nameMatch.hasMatch()) values << nameMatch.captured(1); } ui->label->setText(QString::number(values.size())); }
-
"R was not declared in this scope"
Old compiler? that's C++11. use
const QRegularExpression nameExp("<name>(.+)<\\/name>");
then"stream was not declared in this scope"
change
while (stream.readLineInto(&line))
intowhile (in.readLineInto(&line))
"nameMatch does not name a type"
again old compiler
const QRegularExpressionMatch nameMatch = nameExp.match(line);
"nameMatch was not declared in this scope"
The above solves this too
-
@Lasith said in Getting a specific text from a text file and inserting to a QStringList!:
I use Qt 5.2
That's not supported anymore.
Is it feasible for you to upgrade to a newer version? (Qt 5.10.0 was released last week)