How to can append the value from txt file to the Qlist - qt

How I can to insert the value from txt file in to the Qlist...
QList<QString> list_StRead;
list_StRead.insert();
I can sorting txt file ... its mean that my file is a line by line. than after the insert to the Qlist I want to write in to Qtabelewidget. How I must to do?? u must to be completely understand. see the img file
tnx for all....

Here is the pseudo code.
Please try it. (Not tested, code written in notepad. excuse me any syntax errors).
//Your list
QList<QString> list_StRead;
//Text stream object read data and insert in list.
QTextStream in(&file);
while (!in.atEnd())
{
QString line = in.readLine(); //read one line at a time
list_StRead.push_back(line);
}
//loop your list
for(int i =0; i<list_StRead.size(); i++)
{
//Add by create your tablewidget item and append it.
YourTableWidget->setItem(rowNumber,colNumber,new QTableWidgetItem(list_StRead.at(i)))
}

Related

Add String from textEdit to a QStack

I am trying to capture the contents from textEdit and add it to a QStack. The content I am splitting so to be able to reverse the order of the sentence captured. I already have that part covered, but I want to be able to convert from QStringList to be pushed to the QStack. This is what I have:
void notepad::on_actionReversed_Text_triggered()
{
QString unreversed = ui->textEdit->toPlainText();
QStringList ready = unreversed.split(QRegExp("(\\s|\\n|\\r)+"), QString::SkipEmptyParts);
QStack<QString> stack;
stack.push(ready);
QString result;
while (!stack.isEmpty())
{
result += stack.pop();
ui->textEdit->setText(result);
}
}
QStack::push only takes objects of it's template type.
i.e. In your case you must push QString's onto the QStack<QString>, and not a list.
So, iterate the list of strings pushing each one in turn.
foreach (const QString &str, ready) {
stack.push(str);
}
Something else that is wrong is that you are updating textEdit inside the for loop. You actually want to build up the string in the loop and afterwards update the text.
QString result;
while (!stack.isEmpty()) {
result += stack.pop();
}
ui->textEdit->setText(result);
An alternate answer could be to do away with the stack and just iterate the QStringList ready in reverse order to build up result string.

How to report progress without going through the entire file before I process

I have to parse a big file with several thousand records. I want to display a progress bar, but I do not know the number of recordings in advance. Do I have to roll over this file twice?
The first to know the number of recording.
The second to perform the treatment
Or is there a more simple way to get the number of records without going through the entire file before I process ?
My code snippet :
void readFromCSV(const QString &filename){
int line_count=0;
QString line;
QFile file(filename);
if(!file.open(QFile::ReadOnly | QFile::Text))
return;
QTextStream in(&file);
while(!in.atEnd()){ //First loop
line = in.readLine();
line_count++;
}
while (!in.atEnd()) { //Second loop
...
line = in.readLine();
process();
...
}
}
Thank you for help
This question is different from the one here : counting the number of lines in a text file
1) The loop process is already done. In this case it is prevention of double shooting.
2) The code is a QT one, not a C++ fonction to add as a redundancy
I think there is no way to count lines without reading the file at least once. To avoid it I wouldn't rely on the number of lines, but rather on how much data I have been read. Here is how I would solve this problem:
QFile file(fileName);
file.open(QFile::ReadOnly | QFile::Text);
const auto size = file.size();
QTextStream in(&file);
while (!in.atEnd()) {
auto line = in.readLine();
// Process line.
// [..]
// Calculate the progress in percent.
auto remains = file.bytesAvailable();
auto progress = ((size - remains) * 100) / size;
printf("progress: %d%%\r", progress);
}

check if a file extension is part of a given list

I am trying to make a simple widget which contains a lineedit which shows the file name and a button to open a filedialog.
and now I want to check if the file-extension is valid, in this case, a image file ending with jpg, png or bmp. I solved this with QFileInfo and QList, this code is in my btn_clicked slot:
QString filename = QFileDialog::getOpenFileName(this, tr("Select an image File", "", tr("Image Files (*.bmp *.jpg *.png);; All Files(*)"));
QList<QString> ext_list;
ext_list<<"bmp"<<"jpg"<<"png";
QFileInfo fi(filename);
QString ext = fi.suffix();
if (ext_list.contains(ext)){
// lineedit->setText(filename);
}
else {
QMessageBox msgBox;
msgBox.critical(0, "Error", "You must select a valid image file");
it works, but is there a more simple/elegant way to achieve the goal? Thx for your help.
You might be interested by the setNameFilters function : http://doc.qt.io/qt-5/qfiledialog.html#setNameFilters
Update
If you want to filter images without naming each extensions, you should use QMimeDatabase. This will allow you to define your filter for the QFileDialog and then get a list of extensions to check.
For example with jpeg and png:
QStringList mimeTypeFilters;
mimeTypeFilters << "image/jpeg" << "image/png";
QFileDialog fd;
fd.setFileMode(QFileDialog::ExistingFile);
fd.setMimeTypeFilters(mimeTypeFilters);
fd.exec();
QString filename = fd.selectedFiles().count() == 1 ? fd.selectedFiles().at(0) : "";
QMimeDatabase mimedb;
if(!mimeTypeFilters.contains(mimedb.mimeTypeForFile(filename).name()))
{
// something is wrong here !
}

Filling some QTableWidgetItems with QString from file

I'm trying to fill a QTableWidget from a file that was exported by my program, but when I try to set text to the table cells they just ignore me, nothing happens.
void MainWindow::on_actionOpen_Project_triggered()
{
QString line, fileName;
fileName = QFileDialog::getOpenFileName(this,tr("Open Project"), "", tr("Project Files (*.project)"));
if(!fileName.isEmpty()){
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return;
QTextStream in(&file);
for(int i=0;i<ui->code->rowCount();i++){ // goes through table rows
for(int j=0;j<ui->code->columnCount();j++){ // through table columns
ui->code->setCurrentCell(i,j);
QTableWidgetItem *cell = ui->code->currentItem();
in >> line;
if(!line.isEmpty()){
cell = new QTableWidgetItem(line); // relates the pointer to a new object, because the table is empty.
ui->errorlog->append(line); // just for checking if the string is correct visually.
}
}
}
file.close();
}
}
The errorlog object shows on the screen the correct values opened from the file, however the table is not filled. Any problems found?
This line:
cell = new QTableWidgetItem(line);
doesn't do what you think it does. Assigning the cell doesn't change anything in the table – cell is just a local variable, overwriting it doesn't have any effect elsewhere.
You (probably) want to do something like this instead:
cell->setText(line);
Or (if you don't really need to change the current item):
ui->code->item(i,j)->setText(line);
If those give you a segfault, it's that you haven't set the table's widget items yet. In that case, you should do something like:
QTableWidgetItem *cell = ui->code->item(i,j);
if (!cell) {
cell = new QTableWidgetItem;
ui->code->setItem(i,j,cell);
}
if (!line.isEmpty()) {
cell->setText(line);
}
This will populate all the cells with QTableWidgetItems the first time this function is called, and reuse them subsequently.

read a text file to QStringList

I have a text file. I need to read it to a QStringList. there are no line seperators. I mean each line in the text file is in a new line. So is there anyway i can do this?
I assume that every line should be a separate string in the list. Use QTextStream::readLine() in a cycle and on each step append the returned value to the QStringList. Like this:
QStringList stringList;
QFile textFile;
//... (open the file for reading, etc.)
QTextStream textStream(&textFile);
while (true)
{
QString line = textStream.readLine();
if (line.isNull())
break;
else
stringList.append(line);
}
QFile TextFile;
//Open file for reading
QStringList SL;
while(!TextFile.atEnd())
SL.append(TextFile.readLine());
If the file isn't too big, read the whole content into a QString and then split() it into a QStringList.
I like using the QRegExp version to handle linefeed from different platforms:
QStringList sList = s.split(QRegExp("(\\r\\n)|(\\n\\r)|\\r|\\n"), QString::SkipEmptyParts);
I like my code to be fully indented/paranthesized with obvious variable names (they may take longer to type but are much easier to debug) so would do the following (but changing "myTextFile" and "myStringList" to more sensible names, such as "employeeListTextFile")
QFile myTextFile;
QStringList myStringList;
if (!myTextFile.open(QIODevice::ReadOnly))
{
QMessageBox::information(0, "Error opening file", myTextFile.errorString());
}
else
{
while(!myTextFile.atEnd())
{
myStringList.append(myTextFile.readLine());
}
myTextFile.close();
}
The below code reads the file
QFile File("/file_path");
if(!File.open(QIODevice::ReadOnly));
{
qDebug("Error");
}
QTextStream in(&File);
while(!in.atEnd())
{
qDebug()<<ReadAll;
ReadAll=in.readAll();
}
File.close();
Now the file is closed, now split the new line i.e \n here \r is carriage return
List= ReadAll.split(QRegExp("[\r\n]"),QString::SkipEmptyParts);

Resources