Print Tableview Data with Qprinter

Asked

Viewed 171 times

3

How can I get the data from a TableView add to 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();

1 answer

2

You need to get the model where the QTableView search the data, iterate the items and extract their content using the method QAbstractItemModel::data:

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 method QAbstractItemModel::headerData to get the text of the headers and include them at the beginning of the table.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.