My programming knowledge and experience is very poor. I am using this code block to open the desired file when clicked on a push button ;
QString filename = QFileDialog::getOpenFileName();
QFile file(filename);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
while (!file.atEnd())
{
QByteArray line = file.readLine();
processline(line);
}
And by this line i am showing it on QtextBrowser
void MainWindow::processline(QByteArray paramline)
{
ui->veri_cikis->append(paramline.constData());
}
The data on the file is like this
0;100;0
0;100;24
24;500;24
24;100;6
6;100;6
i have to split the datas by ";" mark and display them on a Qtreewidget columns. How do i do that ? And i have to show each first part on first column and second on second column and so. I have 3 columns in total
I think what you describe is better fit rather to a table view than a tree view. To parse your strings and split them by ';' character you can use QByteArray::split() function. Here is the sample code, that creates and populates table view with items that read from the file:
QFile file(filename);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
QTableWidget *table = new QTableWidget;
int row = 0;
while (!file.atEnd()) {
QByteArray line = file.readLine();
QList<QByteArray> tokens = line.split(';');
int column = 0;
row++;
foreach (QByteArray ba, tokens) {
QTableWidgetItem *item = new QTableWidgetItem(ba);
table->setItem(row, column++, item);
}
}
Related
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.
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);
//...
I have a text file that contains many vocabularies, each vocabulary is separated by a new line.
How can I populate a Qt ListView with vocabularies from the text file?
QStringListModel *model;
// Create model
model = new QStringListModel(this);
QStringList stringList;
// open the file
QFile textFile("/<FullPath>/<fileName>");
if(!textFile.open(QIODevice::ReadOnly)) {
QMessageBox::information(0,"Error",textFile.errorString());
}
// teststream to read from file
QTextStream textStream(&textFile);
while (true)
{
QString line = textStream.readLine();
if (line.isNull())
break;
else
stringList.append(line); // populate the stringlist
}
// Populate the model
model->setStringList(stringList);
// Glue model and view together
ui->listView->setModel(model);
// if you want to add additional feature to listview.
ui->listView->
setEditTriggers(QAbstractItemView::AnyKeyPressed |
QAbstractItemView::DoubleClicked);
You need to read the file line by line, and add to a QStringList, then into listView.
QStringList *allLines = new QStringList(); //Your list for lines from the file.
allLines->clear();
QStringListModel *linesModel = new QStringListModel(*allLines, NULL); //Your model to set to the view.
QFile file("/path/to/yourFileName.txt");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
while (!file.atEnd()) {
QByteArray line = file.readLine(); //Lines are read as QByteArray.
const char *line_c = line.data(); //convert to const char*
QString line_str = QString(QLatin1String(line_c)); //And finally convert to QString
allLines->append(line_str); //Add to the list
}
linesModel->setStringList(*allLines); //Set your model's list your stringlist
listView->setModel(linesModel); //set model of your listView linesModel. You need to use your listView's name, which might be ui->listView.
I am writing a Qt GUI C++ program where I am planning to populate a tabular view, for example a 3X2 table view. Where the texts in the field will be from a .csv file. And along with the text there will also be a small icon/image.
To give an idea of the UI it might be looking somewhat like;
Now adding text to QTable model view I have done using;
QStandardItemModel *model = new QStandardItemModel;
QFile file("/home/aj/beta_test.csv");
if (file.open(QIODevice::ReadOnly))
{
int lineindex = 0; // file line counter
QTextStream in(&file); // read to text stream
while (!in.atEnd()) {
QStringList lineToken;
QString fileLine = in.readLine(); // read one line (separated by "\n")
lineToken = fileLine.split(",", QString::SkipEmptyParts); // parse a line into separate pieces with "," as the delimiter
for (int j = 0; j < lineToken.size(); j++) // load parsed data to model accordingly
{
QString value = lineToken.at(j);
QStandardItem *item = new QStandardItem(value);
model->setItem(lineindex, j, item);
ui->tableView->setModel(model);
}
lineindex++;
}
file.close();
}
Now how to perform adding the image part???
You can use standard method:
item->setIcon(QIcon("path"));
or do this with index (use setData() and Qt::DecorationRole)
After adding you can call resizeRowsToContents() to show full images in your cells.
Also I noticed that you set your model in every iteration. It is not wrong but it is very inefficient (especially when you populate large data), so set your model one time after the loop.
Recently I was working on a gui application & I wanted to save the data of QTableView in a .csv or .txt file. I Used the guidance received during this question which made me think if the reverse is also possible; i.e. if the QTableView can be populated from a .csv or .txt file. Once again I would prefer staying with a model based design such as QTableView instead of item based QTableWidget.
Any code-snippet or tutorial-documentation would be really helpful.
Consider a test.csv file (it could be generated by any text editor):
And the textstream behind is (if generated by programming):
1,2,3,\n4,5,6,\n7,8,9,\n10,11,12,\n13,14,15,
If opened in Microsoft Office Excel, it might looked like:
To read this .csv file to the model of your QTableView:
QStandardItemModel *model = new QStandardItemModel;
QFile file("test.csv");
if (file.open(QIODevice::ReadOnly)) {
int lineindex = 0; // file line counter
QTextStream in(&file); // read to text stream
while (!in.atEnd()) {
// read one line from textstream(separated by "\n")
QString fileLine = in.readLine();
// parse the read line into separate pieces(tokens) with "," as the delimiter
QStringList lineToken = fileLine.split(",", QString::SkipEmptyParts);
// load parsed data to model accordingly
for (int j = 0; j < lineToken.size(); j++) {
QString value = lineToken.at(j);
QStandardItem *item = new QStandardItem(value);
model->setItem(lineindex, j, item);
}
lineindex++;
}
file.close();
}
(You could manipulate the code to meet you table format)
[Result]