QTableView output save as .csv or .txt

RicoRicochet picture RicoRicochet · Dec 8, 2014 · Viewed 9.1k times · Source

I wrote the below code for a qt gui to view the query output in a QTableView(Model oriented). now i want to save this output as a .csv or .txt file. There were suggestions to use QTableWidget(Item oriented) but I would like to stick to the model based approach.

void MainWindow::on_pushButton_clicked()
{
db = QSqlDatabase::addDatabase("QOCI");
db.setHostName("host");
db.setDatabaseName("db");
db.setUserName("uid");
db.setPassword("pw");
db.setPort(port);

QString MyQuery = ui->lineEdit->text();

if (db.open())
{
    qDebug()<<QDateTime::currentDateTime()<<"QUERY DONE SUCCESSFULLY ";

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

}
else
{
    qDebug()<<QDateTime::currentDateTime()<<"YOU FORGOT THE QUERY "<<db.lastError().text();
}

}

any guidelines ???

Answer

Tay2510 picture Tay2510 · Dec 8, 2014

You may customize it according to your actual needs:

// [Collect model data to QString]
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)
}

// [Save to file] (header file <QFile> needed)
// .csv
QFile csvFile("test.csv");    
if(csvFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) {

    QTextStream out(&csvFile);
    out << textData;

    csvFile.close();
} 

// .txt
QFile txtFile("test.txt");    
if(txtFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) {

    QTextStream out(&txtFile);
    out << textData;

    txtFile.close();
}