Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QTableView output save as .csv or .txt

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 ???

like image 589
RicoRicochet Avatar asked Dec 08 '14 07:12

RicoRicochet


1 Answers

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();
} 
like image 107
Tay2510 Avatar answered Sep 18 '22 00:09

Tay2510