コード例 #1
0
ファイル: textdocumentmodel.cpp プロジェクト: KDAB/GammaRay
void TextDocumentModel::fillFrameIterator(const QTextFrame::iterator &it, QStandardItem *parent)
{
    if (QTextFrame *frame = it.currentFrame()) {
        const QRectF b = m_document->documentLayout()->frameBoundingRect(frame);
        QTextTable *table = qobject_cast<QTextTable *>(frame);
        auto item = new QStandardItem;
        if (table) {
            item->setText(tr("Table"));
            appendRow(parent, item, table->format(), b);
            fillTable(table, item);
        } else {
            item->setText(tr("Frame"));
            appendRow(parent, item, frame->frameFormat(), b);
            fillFrame(frame, item);
        }
    }
    const QTextBlock block = it.currentBlock();
    if (block.isValid()) {
        auto item = new QStandardItem;
        item->setText(tr("Block: %1").arg(block.text()));
        const QRectF b = m_document->documentLayout()->blockBoundingRect(block);
        appendRow(parent, item, block.blockFormat(), b);
        fillBlock(block, item);
    }
}
コード例 #2
0
void TextEditWidget::sl_CreateTableAction_Triggered() {
	QTextTable* table = textField->textCursor().currentTable();
	if (table) {
		return;
	}

	textField->textCursor().beginEditBlock();
	table = textField->textCursor().insertTable(2, 2);
	QTextTableFormat format = table->format();

	format.setCellSpacing(0);
	format.setCellPadding(3);
	format.setBorderStyle(QTextFrameFormat::BorderStyle_Solid);

	QTextLength tableWidth(QTextLength::PercentageLength, 50);
	format.setWidth(tableWidth);

	table->setFormat(format);
	textField->textCursor().endEditBlock();

	QTextTableCell cell = table->cellAt(0, 0);
	textField->setTextCursor(cell.firstCursorPosition());
}
コード例 #3
0
void QTextCopyHelper::copy()
{
    if (cursor.hasComplexSelection()) {
        QTextTable *table = cursor.currentTable();
        int row_start, col_start, num_rows, num_cols;
        cursor.selectedTableCells(&row_start, &num_rows, &col_start, &num_cols);

        QTextTableFormat tableFormat = table->format();
        tableFormat.setColumns(num_cols);
        tableFormat.clearColumnWidthConstraints();
        const int objectIndex = dst->formatCollection()->createObjectIndex(tableFormat);

        Q_ASSERT(row_start != -1);
        for (int r = row_start; r < row_start + num_rows; ++r) {
            for (int c = col_start; c < col_start + num_cols; ++c) {
                QTextTableCell cell = table->cellAt(r, c);
                const int rspan = cell.rowSpan();
                const int cspan = cell.columnSpan();
                if (rspan != 1) {
                    int cr = cell.row();
                    if (cr != r)
                        continue;
                }
                if (cspan != 1) {
                    int cc = cell.column();
                    if (cc != c)
                        continue;
                }

                // add the QTextBeginningOfFrame
                QTextCharFormat cellFormat = cell.format();
                if (r + rspan >= row_start + num_rows) {
                    cellFormat.setTableCellRowSpan(row_start + num_rows - r);
                }
                if (c + cspan >= col_start + num_cols) {
                    cellFormat.setTableCellColumnSpan(col_start + num_cols - c);
                }
                const int charFormatIndex = convertFormatIndex(cellFormat, objectIndex);

                int blockIdx = -2;
                const int cellPos = cell.firstPosition();
                QTextBlock block = src->blocksFind(cellPos);
                if (block.position() == cellPos) {
                    blockIdx = convertFormatIndex(block.blockFormat());
                }

                dst->insertBlock(QTextBeginningOfFrame, insertPos, blockIdx, charFormatIndex);
                ++insertPos;

                // nothing to add for empty cells
                if (cell.lastPosition() > cellPos) {
                    // add the contents
                    appendFragments(cellPos, cell.lastPosition());
                }
            }
        }

        // add end of table
        int end = table->lastPosition();
        appendFragment(end, end+1, objectIndex);
    } else {
        appendFragments(cursor.selectionStart(), cursor.selectionEnd());
    }
}
コード例 #4
0
void FormSimularCuotas::generaReporte()
{
    documento = new QTextDocument();
    QTextCursor cursor( documento );
    int cant_filas = 3 + SBCantidad->value();
    QTextTable *tabla = cursor.insertTable( cant_filas, 5 );
    QTextTableFormat formatoTabla = tabla->format();
    formatoTabla.setHeaderRowCount( 1 );
    formatoTabla.setWidth( QTextLength( QTextLength::PercentageLength, 100 ) );
    formatoTabla.setBorderStyle( QTextFrameFormat::BorderStyle_Solid );
    formatoTabla.setBorder( 1 );
    formatoTabla.setCellPadding( 3 );
    formatoTabla.setCellSpacing( 0 );
    tabla->setFormat( formatoTabla );
    tabla->cellAt( 0,0 ).firstCursorPosition().insertHtml( "<b> # Cuota</b>" );
    tabla->cellAt( 0,1 ).firstCursorPosition().insertHtml( "<b> Fecha de pago </b>" );
    tabla->cellAt( 0,2 ).firstCursorPosition().insertHtml( "<b> Cuota </b>" );
    tabla->cellAt( 0,3 ).firstCursorPosition().insertHtml( "<b> Pagado </b> " );
    tabla->cellAt( 0,4 ).firstCursorPosition().insertHtml( "<b> Subtotal </b>" );

    QTextBlockFormat bfizq = tabla->cellAt( 0, 3 ).firstCursorPosition().blockFormat();
    bfizq.setAlignment( Qt::AlignRight );
    // Ingreso los datos
    double subtotal = DSBImporte->value();
    double pagado = DSBEntrega->value();
    // Importe
    tabla->cellAt( 1, 0 ).firstCursorPosition().insertHtml( " " );
    tabla->cellAt( 1, 1 ).firstCursorPosition().insertHtml( "Importe a pagar en cuotas" );
    tabla->cellAt( 1, 2 ).firstCursorPosition().setBlockFormat( bfizq );
    tabla->cellAt( 1, 2 ).firstCursorPosition().insertHtml( QString( "$ %L1" ).arg( subtotal, 10, 'f', 2 ) );
    tabla->cellAt( 1, 3 ).firstCursorPosition().setBlockFormat( bfizq );
    tabla->cellAt( 1, 3 ).firstCursorPosition().insertHtml( QString( "$ %L1" ).arg( 0.0, 10, 'f', 2 ) );
    tabla->cellAt( 1, 4 ).firstCursorPosition().setBlockFormat( bfizq );
    tabla->cellAt( 1, 4 ).firstCursorPosition().insertHtml( QString( "$ %L1" ).arg( subtotal, 10, 'f', 2 ) );
    subtotal -= DSBEntrega->value();
    tabla->cellAt( 2, 0 ).firstCursorPosition().insertHtml( "" );
    tabla->cellAt( 2, 1 ).firstCursorPosition().insertHtml( "Entrega inicial" );
    tabla->cellAt( 2, 2 ).firstCursorPosition().setBlockFormat( bfizq );
    tabla->cellAt( 2, 2 ).firstCursorPosition().insertHtml( QString( "$ %L1" ).arg( DSBEntrega->value(), 10, 'f', 2 ) );
    tabla->cellAt( 2, 3 ).firstCursorPosition().setBlockFormat( bfizq );
    tabla->cellAt( 2, 3 ).firstCursorPosition().insertHtml( QString( "$ %L1" ).arg( pagado, 10, 'f', 2 ) );
    tabla->cellAt( 2, 4 ).firstCursorPosition().setBlockFormat( bfizq );
    tabla->cellAt( 2, 4 ).firstCursorPosition().insertHtml( QString( "$ %L1" ).arg( subtotal, 10, 'f', 2 ) );
    subtotal *= ( 1 + DSBInteres->value() / 100 );
    double valor_cuota = ( ( DSBTotal->value() ) * ( 1 + DSBInteres->value() / 100 ) ) / SBCantidad->value();
    QDate fch = DEInicio->date();
    for( int i = 1; i<=SBCantidad->value(); i++ ) {
        tabla->cellAt( i+2, 0 ).firstCursorPosition().insertHtml( QString( "#%1" ).arg( i ) );
        tabla->cellAt( i+2, 1 ).firstCursorPosition().insertHtml( QString( "%1" ).arg( fch.toString( Qt::SystemLocaleShortDate ) ) );
        fch.addDays( (i-1)*MPlanCuota::diasEnPeriodo( (MPlanCuota::Periodo) CBPeriodo->currentIndex(), fch ) );
        tabla->cellAt( i+2, 2 ).firstCursorPosition().setBlockFormat( bfizq );
        tabla->cellAt( i+2, 2 ).firstCursorPosition().insertHtml( QString( "$ %L1" ).arg( valor_cuota, 10, 'f', 2 ) );
        pagado += valor_cuota;
        tabla->cellAt( i+2, 3 ).firstCursorPosition().setBlockFormat( bfizq );
        tabla->cellAt( i+2, 3 ).firstCursorPosition().insertHtml( QString( "$ %L1" ).arg( pagado, 10, 'f', 2 ) );
        subtotal -= valor_cuota;
        tabla->cellAt( i+2, 4 ).firstCursorPosition().setBlockFormat( bfizq );
        tabla->cellAt( i+2, 4 ).firstCursorPosition().insertHtml( QString( "$ %L1" ).arg( subtotal, 10, 'f', 2 ) );
    }

    // Firma y aclaracion
    cursor.movePosition( QTextCursor::End );
    cursor.insertBlock();
    cursor.insertBlock();
    cursor.insertBlock();
    cursor.insertBlock();
    cursor.insertBlock();
    cursor.insertText( "Firma del contrayente: ___________________________" );
    cursor.insertBlock();
    cursor.insertBlock();
    cursor.insertBlock();
    cursor.insertBlock();
    cursor.insertText( QString::fromUtf8( "Aclaracion: ________________________________________________      DNI:___-__________-___" ) );
    cursor.insertBlock();
    cursor.insertBlock();
    cursor.insertHtml( QString::fromUtf8( "<small>En caso de provocarse un atraso en la fecha de pago de cualquiera de las cuotas, se aplicara el recargo correspondiente tal cual se hace actualmenete con cualquier recibo emitido por nuestra entidad.</small>" ) );

    // Cabecera
    cursor.movePosition( QTextCursor::Start );
    cursor.insertBlock();
#ifdef Q_OS_WIN
    cursor.insertHtml( "<h1>HiComp Computación</h1><br />" );
#else
    cursor.insertHtml( "<h1>" + ERegistroPlugins::getInstancia()->pluginInfo()->empresa() + "</h1><br />" );
#endif
    cursor.insertHtml( "<h2>Plan de cuotas</h2><br /><br />" );
    cursor.insertBlock();
    cursor.insertHtml( QString( "<b>Fecha de Inicio:</b> %1 <br />" ).arg( DEInicio->date().toString( Qt::SystemLocaleLongDate ) ) );
    cursor.insertHtml( QString( "<b>Nombre del cliente:</b> %1 <br />").arg( MClientes::getRazonSocial( _id_cliente ) ) );
    return;
}
コード例 #5
0
void TableFormatter::onTablePropertiesClicked()
{
  QTextCursor cursor(textArea->textCursor());
  QTextTable *table = cursor.currentTable();

  // Если курсор не внутри таблицы, значит свойства таблицы менять не получится
  if(!table)
  {
    QMessageBox msgBox;
    msgBox.setText(tr("Can't modify table properties. Please set cursor into table."));
    msgBox.exec();

    return;
  }

  EditorTablePropertiesForm form;

  // Ширина таблицы
  qDebug() << "Type of table width lenght: " << table->format().width().type();
  if(table->format().width().type()==QTextLength::PercentageLength) // Если ширина указана в процентах
  {
    int tableWidth=(int) table->format().width().rawValue();
    form.setTableWidth( tableWidth );
  }
  else
  {
    // Иначе ширина фиксированная в пикселях, и нужно перевести пиксели в проценты
    qreal tableWidthPix=(int) table->format().width().rawValue();
    qreal pageWidthPix=1;
    qreal tableWidth=1;

    // Если ширина не была задана вообще
    if(tableWidthPix<1)
      tableWidth=50; // Условно берется 50%
    else
    {
      pageWidthPix=textArea->width();
      tableWidth=(tableWidthPix*100.0)/pageWidthPix;
    }

    form.setTableWidth( (int) tableWidth );
  }

  // Толщина линий
  int borderWidth=(int) table->format().border();
  form.setBorderWidth(borderWidth );

  // Цвет фона таблицы
  QColor tableBackground;
  if(table->format().hasProperty(QTextFormat::BackgroundBrush))
   tableBackground=table->format().background().color(); // Фон таблицы задан явно
  else
    tableBackground.setRgb(255,255,255); // Фон таблицы не задан, используется белый цвет
  form.setBackgroundColor(tableBackground);
  qDebug() << "Table background color is: " << tableBackground.name();

  // Выравнивание таблицы
  EditorTablePropertiesForm::TableAlign align=EditorTablePropertiesForm::Left;
  if(table->format().alignment()==Qt::AlignLeft)
    align=EditorTablePropertiesForm::Left;
  else if((table->format().alignment()==Qt::AlignHCenter) || (table->format().alignment()==Qt::AlignJustify))
    align=EditorTablePropertiesForm::Center;
  else if(table->format().alignment()==Qt::AlignRight)
    align=EditorTablePropertiesForm::Right;
  form.setTableAlign( align);


  // Отрисовывается форма редактирования свойств таблицы
  if(!form.exec())
    return;


  // Создаётся новый формат таблицы
  QTextTableFormat newFormat=table->format();

  // Устанавливается новая ширина таблицы
  QTextLength tableWidthLength(QTextLength::PercentageLength, form.getTableWidth());
  newFormat.setWidth( tableWidthLength );

  // Устанавливается новая толщина линий
  newFormat.setBorder( form.getBorderWidth() );
  newFormat.setBorderStyle(QTextFrameFormat::BorderStyle_Solid);
  newFormat.setPadding(0);
  newFormat.setCellPadding(0);
  newFormat.setCellSpacing(-1);

  // Устанавливается цвет фона
  newFormat.setBackground( form.getBackgroundColor() );

  if(form.getTableAlign()==EditorTablePropertiesForm::Left)
    newFormat.setAlignment( Qt::AlignLeft );
  else if(form.getTableAlign()==EditorTablePropertiesForm::Center)
    newFormat.setAlignment( Qt::AlignHCenter );
  else if(form.getTableAlign()==EditorTablePropertiesForm::Right)
    newFormat.setAlignment( Qt::AlignRight );

  // Новый формат устанавливается текущей таблице
  table->setFormat( newFormat );
}
コード例 #6
0
void InformeCierreCaja::hacerResumen( int id_caja, bool ultimo, int id_cierre )
{
    if( id_caja == -1 ) {
        qWarning( "Numero de caja incorrecto" );
        //abort();
        return;
    } else if( ultimo == false && id_cierre == -1 ) {
        qWarning( "El cierre pedido es incorrecto" );
        //abort();
        return;
    }
    // Busco los datos
    MMovimientosCaja *m = new MMovimientosCaja( this );
    if( ultimo ) {
      id_cierre = m->buscarUltimoCierre( id_caja );
      if( id_cierre == -1 ) {
          return;
      }
    }
    QSqlQuery resultados = m->buscarMovimientos( id_caja, id_cierre );
    ///////////////////////////////////////////////////////////////////////////////////////////////////
    // Inicio el renderizado
    QTextCursor cursor( documento );
    int cantidadCol = 6;
    if( preferencias::getInstancia()->value( "Preferencias/Caja/responsable", true ).toBool() ) { cantidadCol++; }
    /////////////////////////////////////
    /// Hago la cabecera de la tabla
    QTextTable *tabla = cursor.insertTable( 1, cantidadCol );
    QTextTableFormat formatoTabla = tabla->format();
    formatoTabla.setHeaderRowCount( 1 );
    formatoTabla.setWidth( QTextLength( QTextLength::PercentageLength, 100 ) );
    tabla->setFormat( formatoTabla );
    tabla->cellAt( 0,0 ).firstCursorPosition().insertHtml( " # Op " );
    tabla->cellAt( 0,1 ).firstCursorPosition().insertHtml( " Fecha/Hora " );
    tabla->cellAt( 0,2 ).firstCursorPosition().insertHtml( " Razon " );
    tabla->cellAt( 0,3 ).firstCursorPosition().insertHtml( " Ingreso " );
    tabla->cellAt( 0,4 ).firstCursorPosition().insertHtml( " Egreso " );
    tabla->cellAt( 0,5 ).firstCursorPosition().insertHtml( " Saldo " );
    if( preferencias::getInstancia()->value( "Preferencias/Caja/responsable", true ).toBool() ) {
        tabla->cellAt( 0, 6 ).firstCursorPosition().insertHtml( " Responsable " );
    }
    // Averiguo el saldo hasta el momento del cierre anterior
    double saldo_anterior = m->saldoEnMovimientoAnteriorA( id_caja, id_cierre );
    while( resultados.next() ) {
        int pos = tabla->rows();
        tabla->insertRows( pos, 1 );
        tabla->cellAt( pos, 0 ).firstCursorPosition().insertHtml( QString( " # %1 " ).arg( resultados.record().value("id_movimiento" ).toInt() ) );
        tabla->cellAt( pos, 1 ).firstCursorPosition().insertHtml( resultados.record().value("fecha_hora" ).toDateTime().toString( Qt::SystemLocaleDate ) );
        tabla->cellAt( pos, 2 ).firstCursorPosition().insertHtml( resultados.record().value("razon" ).toString() );
        if( resultados.record().value( "cierre" ).toBool() == false ) {
            // Ingreso
            double haber = resultados.record().value( "ingreso" ).toDouble();
            saldo_anterior += haber;
            tabla->cellAt( pos, 3 ).firstCursorPosition().insertHtml( QString( " $ %L1" ).arg( haber ) );
            // Egreso
            double debe = resultados.record().value( "egreso" ).toDouble();
            saldo_anterior -= debe;
            tabla->cellAt( pos, 4 ).firstCursorPosition().insertHtml( QString( " $ %L1" ).arg( debe ) );
            // Subtotal hasta el momento
            tabla->cellAt( pos, 5 ).firstCursorPosition().insertHtml( QString( " $ %L1" ).arg( saldo_anterior ) );
        } else {
            saldo_anterior += resultados.record().value( "ingreso" ).toDouble();
            tabla->cellAt( pos, 5 ).firstCursorPosition().insertHtml( QString( " $ %L1" ).arg( saldo_anterior ) );
        }
        if( preferencias::getInstancia()->value( "Preferencias/Caja/responsable", true ).toBool() ) {
            tabla->cellAt( pos, 6 ).firstCursorPosition().insertHtml( resultados.record().value( "responsable" ).toString() );
        }
    }
    // Saldos finales
    cursor.movePosition( QTextCursor::End );
    cursor.insertBlock();
    cursor.insertHtml( QString( "<b>Saldo Final:</b>   $  %L1" ).arg( saldo_anterior ) );
    cursor.insertBlock();
    if( preferencias::getInstancia()->value( "Preferencias/Caja/firma", true ).toBool() ) {
        cursor.insertBlock();
        cursor.insertText( "Controlado por: ________________________" );
        cursor.insertBlock();
        cursor.insertBlock();
        cursor.insertText( "Firma: ____________" );
    }
    // Termino el resumen
    cursor.movePosition( QTextCursor::Start );
    cursor.insertBlock();
    if( preferencias::getInstancia()->value( "Preferencias/Caja/logo" ).toBool() ) {
        //cursor.insertImage( ERegistroPlugins::pluginInfo()->imagenPrograma() );
        cursor.insertImage( ":/imagenes/gestotux32.png" );
    }
    cursor.insertHtml( "<h1>Cierre de Caja</h1>" );
    cursor.insertBlock();
    cursor.insertHtml( QString( "<b>Fecha de Cierre:</b> %1 <br />" ).arg( QDateTime::currentDateTime().toString( Qt::SystemLocaleLongDate ) ) );
    cursor.insertHtml( QString( "<b>Caja:</b> %1<br />").arg( MCajas::nombreCaja( id_caja ) ) );
    return;
}
コード例 #7
0
ファイル: kwqtableview.cpp プロジェクト: KDE/kwordquiz
void KWQTableView::createPages(QPrinter *printer, QTextDocument *textDoc, bool sendToPrinter)
{
  printer->setFullPage(true);
  int myDpi = printer->logicalDpiY();

  if (Prefs::printStyle() == Prefs::EnumPrintStyle::Flashcard) {
    printer->setOrientation(QPrinter::Landscape);

    int cardWidth = qRound(5 * qreal(myDpi));
    int cardHeight = qRound(3 * qreal(myDpi));

    QTextTable *table = textDoc->rootFrame()->lastCursorPosition().insertTable(model()->rowCount(), 2);

    QTextTableFormat tableFormat = table->format();
    tableFormat.setHeaderRowCount(0);
    tableFormat.setBorderStyle(QTextFrameFormat::BorderStyle_None);
    tableFormat.setCellSpacing(0);
    tableFormat.setCellPadding(0);

    QVector<QTextLength> constraints;
    constraints.append(QTextLength(QTextLength::FixedLength, cardWidth));
    constraints.append(QTextLength(QTextLength::FixedLength, cardWidth));

    tableFormat.setColumnWidthConstraints(constraints);
    table->setFormat(tableFormat);

    QTextBlockFormat headerFormat;
    headerFormat.setAlignment(Qt::AlignLeft);

    QTextCharFormat headerCharFormat;
    headerCharFormat.setFont(QFontDatabase::systemFont(QFontDatabase::GeneralFont));

    QTextBlockFormat cellFormat;
    cellFormat.setAlignment(Qt::AlignCenter);

    QTextCharFormat cellCharFormat;
    cellCharFormat.setFont(Prefs::editorFont());

    QTextFrameFormat cardFormat;
    cardFormat.setBorder(1);
    cardFormat.setBorderStyle(QTextFrameFormat::BorderStyle_Solid);
    cardFormat.setBorderBrush(QBrush(Qt::black));
    cardFormat.setWidth(QTextLength(QTextLength::FixedLength, cardWidth));
    cardFormat.setHeight(QTextLength(QTextLength::FixedLength, cardHeight));
    cardFormat.setPadding(qRound(0.25 * myDpi));

    QTextFrameFormat lineFormat;
    lineFormat.setBorder(1);
    lineFormat.setBorderStyle(QTextFrameFormat::BorderStyle_Solid);
    lineFormat.setBorderBrush(QBrush(Qt::black));
    lineFormat.setWidth(QTextLength(QTextLength::FixedLength, qRound(4.5 * myDpi)));
    lineFormat.setHeight(1.1); //1 is drawn as a box whereas this is drawn as a line. Strange...
    lineFormat.setPadding(0);

    QTextFrame *card;
    for (int i = 0; i < model()->rowCount(); i++) {
      for (int j = 0; j < model()->columnCount(); j++) {
        cardFormat.setPosition(QTextFrameFormat::FloatLeft);
        card = table->cellAt(i, j).firstCursorPosition().insertFrame(cardFormat);
        card->lastCursorPosition().insertText(model()->headerData(j, Qt::Horizontal, Qt::DisplayRole).toString(), headerCharFormat);
        card->lastCursorPosition().insertFrame(lineFormat);
        card->lastCursorPosition().insertBlock();
        card->lastCursorPosition().insertBlock();
        card->lastCursorPosition().insertBlock(cellFormat, cellCharFormat);
        card->lastCursorPosition().insertText(model()->data(model()->index(i, j)).toString(), cellCharFormat);
      }
    }
  }
  else
  {
    textDoc->rootFrame()->lastCursorPosition().insertText(QStringLiteral("kwordquiz %1").arg(KWQ_VERSION));

    if (Prefs::printStyle() == Prefs::EnumPrintStyle::Exam)
      textDoc->rootFrame()->lastCursorPosition().insertText(' ' + i18n("Name:_____________________________ Date:__________"));

    QTextTable* table;
    if (Prefs::printStyle() == Prefs::EnumPrintStyle::Exam)
      table = textDoc->rootFrame()->lastCursorPosition().insertTable(model()->rowCount() + 1, model()->columnCount() + 2);
    else
      table = textDoc->rootFrame()->lastCursorPosition().insertTable(model()->rowCount() + 1, model()->columnCount() + 1);

    QTextTableFormat tableFormat = table->format();
    tableFormat.setHeaderRowCount(1);
    tableFormat.setBorder(1);
    tableFormat.setBorderStyle(QTextFrameFormat::BorderStyle_Solid);
    tableFormat.setCellSpacing(0);
    tableFormat.setBorderBrush(QBrush(Qt::black));
    tableFormat.setCellPadding(2);

    QVector<QTextLength> constraints;
    constraints.append(QTextLength(QTextLength::FixedLength, verticalHeader()->width()));
    constraints.append(QTextLength(QTextLength::FixedLength, columnWidth(0)));
    constraints.append(QTextLength(QTextLength::FixedLength, columnWidth(1)));
    if (Prefs::printStyle() == Prefs::EnumPrintStyle::Exam)
        constraints.append(QTextLength(QTextLength::FixedLength, 50));
    tableFormat.setColumnWidthConstraints(constraints);

    table->setFormat(tableFormat);

    QTextBlockFormat headerFormat;
    headerFormat.setAlignment(Qt::AlignHCenter);

    QTextCharFormat headerCharFormat;
    headerCharFormat.setFont(QFontDatabase::systemFont(QFontDatabase::GeneralFont));

    QTextCursor cellCursor;
    cellCursor = table->cellAt(0, 1).firstCursorPosition();
    cellCursor.mergeBlockFormat(headerFormat);
    cellCursor.mergeCharFormat(headerCharFormat);
    cellCursor.insertText(model()->headerData(0, Qt::Horizontal, Qt::DisplayRole).toString());

    cellCursor = table->cellAt(0, 2).firstCursorPosition();
    cellCursor.mergeBlockFormat(headerFormat);
    cellCursor.mergeCharFormat(headerCharFormat);
    cellCursor.insertText(model()->headerData(1, Qt::Horizontal, Qt::DisplayRole).toString());

    if (Prefs::printStyle() == Prefs::EnumPrintStyle::Exam) {
      cellCursor = table->cellAt(0, 3).firstCursorPosition();
      cellCursor.mergeBlockFormat(headerFormat);
      cellCursor.mergeCharFormat(headerCharFormat);
      cellCursor.insertText(i18n("Score"));
    }

    headerCharFormat = cellCursor.charFormat();
    QTextCharFormat cellCharFormat = cellCursor.charFormat();
    cellCharFormat.setFont(Prefs::editorFont());

    for (int i = 0; i < model()->rowCount(); i++) {
      table->cellAt(i + 1, 0).firstCursorPosition().insertText(model()->headerData(i, Qt::Vertical, Qt::DisplayRole).toString(), headerCharFormat);
      table->cellAt(i + 1, 1).firstCursorPosition().insertText(model()->data(model()->index(i, 0)).toString(), cellCharFormat);
      if (Prefs::printStyle() == Prefs::EnumPrintStyle::List)
        table->cellAt(i + 1, 2).firstCursorPosition().insertText(model()->data(model()->index(i, 1)).toString(), cellCharFormat);
    }
  }

  if (sendToPrinter)
    textDoc->print(printer);
}