mainform.cpp:#include "mainform.h"//MainForm::MainForm( QWidget * parent, Qt::WFlags f) : QMainWindow(parent, f){ setupUi(this); connect(pushButton, SIGNAL(clicked()), this, SLOT(OpenFile()));}//void MainForm::OpenFile(){QString fileName = QFileDialog::getOpenFileName(this);QFile file (fileName); if (file.open(QIODevice::ReadOnly)) { QTextStream stream(&file); QString str; stream.setCodec("UTF-8"); QTableWidget* tbl = new QTableWidget; tbl->setColumnCount(3); tbl->setRowCount(10); // lst << "First" << "Second" << "Third"; // tbl->setHorizontalHeaderLabels(lst); tbl->setColumnCount(20); tbl->setRowCount(2); int row=0,col=0; while (!stream.atEnd()) { str = stream.readLine(); QStringList fields = str.split(' '); int f = fields.takeLast().toInt(); for (int i=0; i<=f; ++i) { QTableWidgetItem *item = new QTableWidgetItem; item->setData(fields); tbl->setItem(row, i, item); } } if (stream.status() != QTextStream::Ok) { qDebug() << "Ошибка чтения файла"; } file.close(); tbl->show();} }mainform.h:#ifndef MAINFORM_H#define MAINFORM_H//#include <QMainWindow>#include "ui_mainwindow.h"#include <QtGui>#include <QTextStream>#include <QTableWidget>#include <QTableWidgetItem>#include <QStringList>//class MainForm : public QMainWindow, public Ui::MainWindow{Q_OBJECTpublic: MainForm( QWidget * parent = 0, Qt::WFlags f = 0 ); //QTableWidget *tbl; // ??? //QTableWidgetItem ptwi = 0; QStringList lst;private slots: void OpenFile();};#endif
int f = fields.takeLast().toInt();for (int i=0; i<=f; ++i){ QTableWidgetItem *item = new QTableWidgetItem; item->setData(fields); // <---------- Вставил весь список залпом !!! tbl->setItem(row, i, item); }
int i=0;// для каждой строки из списка строкforeach (QString str, fields){ QTableWidgetItem *item = new QTableWidgetItem; item->setData(str); // <---------- Вставил один элемент списка tbl->setItem(row, i++, item);}
...item->setData(str); ...
void MainForm::OpenFile(){QString fileName = QFileDialog::getOpenFileName(this);QFile file (fileName); if (file.open(QIODevice::ReadOnly)) { QTextStream stream(&file); stream.setCodec("CP-866"); QTableWidget* tbl = new QTableWidget; lst << "First" << "Second" << "Third"; tbl->setHorizontalHeaderLabels(lst); tbl->setColumnCount(5); tbl->setRowCount(5); int f=0, row=0,col=0, tt=0, vv=0; QString str; QString fff, ggg; QList<QString> gg; QStringList fields; while (!stream.atEnd()) { str = stream.readLine(); //chtenie stroki str = str.simplified(); //ubiraet pustie probeli v stroke if (tt<=3) fields = str.split(","); if (tt>3) fields = str.split(' '); tbl->setColumnCount(f); tbl->setRowCount(tt+1); gg = fields; f = fields.size(); for (int i=0; i<=(f-1); ++i) { fff = gg.at(i); QTableWidgetItem *item = new QTableWidgetItem; item->setText(QString(fff)); tbl->setItem(tt, i, item); } ++tt; } if (stream.status() != QTextStream::Ok) { qDebug() << "Р_С_РёР+РєР° С╪С'РчР_РёС_ С"айР>Р°"; } file.close(); tbl->show();}
while (!stream.atEnd()){... qApp->processEvents();...}
str = stream.readLine();