Printing TableView data with QPrinter

3

How can I get the data of a TableView add in layout html and print with QPrinter ?

Code:

   QString html;
   html = "<div>Titulo</div>"
          "<div>etc</div>"
          "<div>etc</div>"
          "<div>"+ ui->tableView->+"</div>"; << tableView


   QPrinter printer;

   QPainter painter;
   painter.begin(&printer);
   painter.drawText(100, 100, 500, 500,Qt::AlignLeft | Qt::AlignTop, html);
   painter.end();
    
asked by anonymous 22.03.2014 / 17:33

1 answer

2

You need to get model from where QTableView looks for the data, iterate through the items, and extract its contents using the QAbstractItemModel::data method:

html += "<table>";
QAbstractItemModel* model = ui->tableView->model();
int rowCount = model->rowCount();
int columnCount = model->columnCount();
for (int row = 0; row < rowCount; row++) {
    html += "<tr>";
    for (int column = 0; column < columnCount; column++) {
        QModelIndex index = model->index(row, column);
        QString text = model->data(index).toString();
        html += "<td>" + text + "</td>";
    }
    html += "</tr>";
}
html += "</table>";

Similarly, you can use the QAbstractItemModel::headerData method to get the text of the headers and include them at the beginning of the table.

    
06.08.2014 / 23:37