QTableView export to .csv number of rows fetched i

2019-02-11 05:08发布

I wrote a gui program which will connect to an oracle db an retrieve data after a query is typed. the retrieved data is shown in a QTableView table model widget. and later the result of the QTableView is exported to a .csv file

QString MyQuery = ui->lineQuery->text();
db.open();
QSqlQuery query(MyQuery,db);

if(query.exec())
{
    qDebug()<<QDateTime::currentDateTime()<<"QUERY SUCCESS ";
    ui->queryButton->setStyleSheet("QPushButton {background-color: rgb(0, 255, 0);}");

    this->model=new QSqlQueryModel();
    model->setQuery(MyQuery);
    ui->tableViewOra->setModel(model);

    QString textData;
    int rows=model->rowCount();
    int columns=model->columnCount();

    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < columns; j++)
        {
            textData += model->data(model->index(i,j)).toString();
            textData += ", ";      // for .csv file format
        }
        textData += "\n";             // (optional: for new line segmentation)
    }

    QFile csvfile("/home/aj/ora_exported.csv");
    if(csvfile.open(QIODevice::WriteOnly|QIODevice::Truncate))
    {
        QTextStream out(&csvfile);
        out<<textData;
    }
    csvfile.close();
}

now the problem is, during a query I observed there are 543 rows visible in the QTableView (which is correct cause there are 543 entries). But when the .csv file is exported, only 256 rows are there.

Is there any variable size constraint that I am unaware about ???

Which variables should be taken care of if I want to export .csv files of upto 1000 rows approx ??? thanks.

1条回答
对你真心纯属浪费
2楼-- · 2019-02-11 05:38

I think when you first read model->rowCount() the model has not fetched all the results completely. Although it will fetch more later when table view is displayed resulting in a full display of rows in the table view.

Try to use QSqlQueryModel::fetchMore before reading the row count :

while (model->canFetchMore())
   model->fetchMore();

int rows=model->rowCount();
int columns=model->columnCount();

[Additional information from Tay2510]:

You could just change the file open flag

if(csvfile.open(QIODevice::WriteOnly|QIODevice::Truncate))

to

if(csvfile.open(QIODevice::WriteOnly))

The former will overwrite the same file while the latter append data on it.

查看更多
登录 后发表回答