// Действия при нажатии кнопки создания новой таблицы
void TableFormatter::onCreatetableClicked(void)
{
  // Создается и запускается диалог создания новой таблицы
  EditorAddTableForm dialog;
  if(dialog.exec()!=QDialog::Accepted) return;

  // Выясняются введенные в диалоге данные
  int tableColumns=dialog.get_columns();
  int tableRows=dialog.get_rows();
  int tableWidth=dialog.get_width();

  // Целочислительный формат ширины таблицы преобразуется в проценты
  QTextLength tableWidthInPercent(QTextLength::PercentageLength, tableWidth);

  // Создается форматирование таблицы
  QTextTableFormat tableFormat;
  tableFormat.setWidth(tableWidthInPercent);
  tableFormat.setAlignment(Qt::AlignHCenter);
  tableFormat.setBorder(1);
  tableFormat.setBorderStyle(QTextFrameFormat::BorderStyle_Solid);
  tableFormat.setPadding(0);
  tableFormat.setCellPadding(0);
  tableFormat.setCellSpacing(-1);

  // Добавляется таблица с нужными размерами и форматированием
  // QTextTable *table=textarea->textCursor().insertTable(table_rows, table_columns, table_format);
  textArea->textCursor().insertTable(tableRows, tableColumns, tableFormat);

  return;
}
Exemple #2
0
ChatView::ChatView(const QString &_ownName, QWidget *parent)
	: QTextEdit(parent), ownName(_ownName)
{
	setTextInteractionFlags(Qt::TextSelectableByMouse);
	
	QTextTableFormat format;
	format.setBorderStyle(QTextFrameFormat::BorderStyle_None);
	table = textCursor().insertTable(1, 3, format);
}
Exemple #3
0
void CPrint::addTable(QTextCursor &cursor,int rows,int cols,QStringList headers)
{
   QTextTableFormat tableFormat;
   tableFormat.setBorder(1);
   tableFormat.setBorderStyle(QTextTableFormat::BorderStyle_Solid);

   tableFormat.setHeaderRowCount(1);
   QTextTable *table=cursor.insertTable(rows+1,cols,tableFormat);
   cursor.movePosition(QTextCursor::End);
}
void KDReports::AbstractTableElement::fillTableFormat( QTextTableFormat& tableFormat, QTextCursor& textDocCursor ) const
{
    if ( d->m_width ) {
        if ( d->m_unit == Millimeters ) {
            tableFormat.setWidth( QTextLength( QTextLength::FixedLength, mmToPixels( d->m_width ) ) );
        } else {
            tableFormat.setWidth( QTextLength( QTextLength::PercentageLength, d->m_width ) );
        }
    }

    tableFormat.setBorder( border() );
#if QT_VERSION >= 0x040300
    tableFormat.setBorderBrush( borderBrush() );
    tableFormat.setBorderStyle( QTextFrameFormat::BorderStyle_Solid );
#endif
    tableFormat.setCellPadding( mmToPixels( padding() ) );
    tableFormat.setCellSpacing( -1 ); // HTML-like table borders look so old century
    if ( d->m_fontSpecified ) {
        QTextCharFormat charFormat = textDocCursor.charFormat();
        charFormat.setFont( d->m_defaultFont );
        textDocCursor.setCharFormat( charFormat );
    }
}
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());
}
Exemple #6
0
/** "Help message" or "About" dialog box */
HelpMessageDialog::HelpMessageDialog(QWidget *parent, bool about) :
    QDialog(parent),
    ui(new Ui::HelpMessageDialog)
{
    ui->setupUi(this);

    QString version = tr("Beardcoin Core") + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion());
    /* On x86 add a bit specifier to the version so that users can distinguish between
     * 32 and 64 bit builds. On other architectures, 32/64 bit may be more ambigious.
     */
#if defined(__x86_64__)
    version += " " + tr("(%1-bit)").arg(64);
#elif defined(__i386__ )
    version += " " + tr("(%1-bit)").arg(32);
#endif

    if (about)
    {
        setWindowTitle(tr("About Beardcoin Core"));

        /// HTML-format the license message from the core
        QString licenseInfo = QString::fromStdString(LicenseInfo());
        QString licenseInfoHTML = licenseInfo;
        // Make URLs clickable
        QRegExp uri("<(.*)>", Qt::CaseSensitive, QRegExp::RegExp2);
        uri.setMinimal(true); // use non-greedy matching
        licenseInfoHTML.replace(uri, "<a href=\"\\1\">\\1</a>");
        // Replace newlines with HTML breaks
        licenseInfoHTML.replace("\n\n", "<br><br>");

        ui->aboutMessage->setTextFormat(Qt::RichText);
        ui->scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
        text = version + "\n" + licenseInfo;
        ui->aboutMessage->setText(version + "<br><br>" + licenseInfoHTML);
        ui->aboutMessage->setWordWrap(true);
        ui->helpMessage->setVisible(false);
    } else {
        setWindowTitle(tr("Command-line options"));
        QString header = tr("Usage:") + "\n" +
                         "  beardcoin-qt [" + tr("command-line options") + "]                     " + "\n";
        QTextCursor cursor(ui->helpMessage->document());
        cursor.insertText(version);
        cursor.insertBlock();
        cursor.insertText(header);
        cursor.insertBlock();

        QString coreOptions = QString::fromStdString(HelpMessage(HMM_BITCOIN_QT));
        text = version + "\n" + header + "\n" + coreOptions;

        QTextTableFormat tf;
        tf.setBorderStyle(QTextFrameFormat::BorderStyle_None);
        tf.setCellPadding(2);
        QVector<QTextLength> widths;
        widths << QTextLength(QTextLength::PercentageLength, 35);
        widths << QTextLength(QTextLength::PercentageLength, 65);
        tf.setColumnWidthConstraints(widths);

        QTextCharFormat bold;
        bold.setFontWeight(QFont::Bold);

        Q_FOREACH (const QString &line, coreOptions.split("\n")) {
            if (line.startsWith("  -"))
            {
                cursor.currentTable()->appendRows(1);
                cursor.movePosition(QTextCursor::PreviousCell);
                cursor.movePosition(QTextCursor::NextRow);
                cursor.insertText(line.trimmed());
                cursor.movePosition(QTextCursor::NextCell);
            } else if (line.startsWith("   ")) {
                cursor.insertText(line.trimmed()+' ');
            } else if (line.size() > 0) {
                //Title of a group
                if (cursor.currentTable())
                    cursor.currentTable()->appendRows(1);
                cursor.movePosition(QTextCursor::Down);
                cursor.insertText(line.trimmed(), bold);
                cursor.insertTable(1, 2, tf);
            }
        }

        ui->helpMessage->moveCursor(QTextCursor::Start);
        ui->scrollArea->setVisible(false);
        ui->aboutLogo->setVisible(false);
    }
}
/** "Help message" or "About" dialog box */
HelpMessageDialog::HelpMessageDialog(QWidget *parent, HelpMode helpMode) :
    QDialog(parent),
    ui(new Ui::HelpMessageDialog)
{
    ui->setupUi(this);

    QString version = tr("Terracoin Core") + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion());
    /* On x86 add a bit specifier to the version so that users can distinguish between
     * 32 and 64 bit builds. On other architectures, 32/64 bit may be more ambigious.
     */
#if defined(__x86_64__)
    version += " " + tr("(%1-bit)").arg(64);
#elif defined(__i386__ )
    version += " " + tr("(%1-bit)").arg(32);
#endif

    if (helpMode == about)
    {
        setWindowTitle(tr("About Terracoin Core"));

        /// HTML-format the license message from the core
        QString licenseInfo = QString::fromStdString(LicenseInfo());
        QString licenseInfoHTML = licenseInfo;

        // Make URLs clickable
        QRegExp uri("<(.*)>", Qt::CaseSensitive, QRegExp::RegExp2);
        uri.setMinimal(true); // use non-greedy matching
        licenseInfoHTML.replace(uri, "<a href=\"\\1\">\\1</a>");
        // Replace newlines with HTML breaks
        licenseInfoHTML.replace("\n\n", "<br><br>");

        ui->aboutMessage->setTextFormat(Qt::RichText);
        ui->scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
        text = version + "\n" + licenseInfo;
        ui->aboutMessage->setText(version + "<br><br>" + licenseInfoHTML);
        ui->aboutMessage->setWordWrap(true);
        ui->helpMessage->setVisible(false);
    } else if (helpMode == cmdline) {
        setWindowTitle(tr("Command-line options"));
        QString header = tr("Usage:") + "\n" +
            "  terracoin-qt [" + tr("command-line options") + "]                     " + "\n";
        QTextCursor cursor(ui->helpMessage->document());
        cursor.insertText(version);
        cursor.insertBlock();
        cursor.insertText(header);
        cursor.insertBlock();

        std::string strUsage = HelpMessage(HMM_BITCOIN_QT);
        const bool showDebug = GetBoolArg("-help-debug", false);
        strUsage += HelpMessageGroup(tr("UI Options:").toStdString());
        if (showDebug) {
            strUsage += HelpMessageOpt("-allowselfsignedrootcertificates", strprintf("Allow self signed root certificates (default: %u)", DEFAULT_SELFSIGNED_ROOTCERTS));
        }
        strUsage += HelpMessageOpt("-choosedatadir", strprintf(tr("Choose data directory on startup (default: %u)").toStdString(), DEFAULT_CHOOSE_DATADIR));
        strUsage += HelpMessageOpt("-lang=<lang>", tr("Set language, for example \"de_DE\" (default: system locale)").toStdString());
        strUsage += HelpMessageOpt("-min", tr("Start minimized").toStdString());
        strUsage += HelpMessageOpt("-rootcertificates=<file>", tr("Set SSL root certificates for payment request (default: -system-)").toStdString());
        strUsage += HelpMessageOpt("-splash", strprintf(tr("Show splash screen on startup (default: %u)").toStdString(), DEFAULT_SPLASHSCREEN));
        strUsage += HelpMessageOpt("-resetguisettings", tr("Reset all settings changed in the GUI").toStdString());
        if (showDebug) {
            strUsage += HelpMessageOpt("-uiplatform", strprintf("Select platform to customize UI for (one of windows, macosx, other; default: %s)", BitcoinGUI::DEFAULT_UIPLATFORM));
        }
        QString coreOptions = QString::fromStdString(strUsage);
        text = version + "\n" + header + "\n" + coreOptions;

        QTextTableFormat tf;
        tf.setBorderStyle(QTextFrameFormat::BorderStyle_None);
        tf.setCellPadding(2);
        QVector<QTextLength> widths;
        widths << QTextLength(QTextLength::PercentageLength, 35);
        widths << QTextLength(QTextLength::PercentageLength, 65);
        tf.setColumnWidthConstraints(widths);

        QTextCharFormat bold;
        bold.setFontWeight(QFont::Bold);

        Q_FOREACH (const QString &line, coreOptions.split("\n")) {
            if (line.startsWith("  -"))
            {
                cursor.currentTable()->appendRows(1);
                cursor.movePosition(QTextCursor::PreviousCell);
                cursor.movePosition(QTextCursor::NextRow);
                cursor.insertText(line.trimmed());
                cursor.movePosition(QTextCursor::NextCell);
            } else if (line.startsWith("   ")) {
                cursor.insertText(line.trimmed()+' ');
            } else if (line.size() > 0) {
                //Title of a group
                if (cursor.currentTable())
                    cursor.currentTable()->appendRows(1);
                cursor.movePosition(QTextCursor::Down);
                cursor.insertText(line.trimmed(), bold);
                cursor.insertTable(1, 2, tf);
            }
        }

        ui->helpMessage->moveCursor(QTextCursor::Start);
        ui->scrollArea->setVisible(false);
        ui->aboutLogo->setVisible(false);
    } else if (helpMode == pshelp) {
Exemple #8
0
bool PriceListPrinter::printODT( PriceListPrinter::PrintPriceItemsOption printOption,
                                 const QList<int> &fieldsToPrint,
                                 int priceDataSetToPrintInput,
                                 bool printPriceList,
                                 bool printPriceAP,
                                 bool APgroupPrAm,
                                 const QString &fileName,
                                 double pageWidth,
                                 double pageHeight,
                                 Qt::Orientation paperOrientation) {
    double borderWidth = 1.0f;
    if( m_d->priceList ){
        int priceDataSetToPrint = 0;
        // controlliamo se il valore di input è corretto
        if( priceDataSetToPrintInput >= 0 && priceDataSetToPrintInput < m_d->priceList->priceDataSetCount() ){
            priceDataSetToPrint = priceDataSetToPrintInput;
        }

        QTextDocument doc;
        QTextCursor cursor(&doc);

        if( paperOrientation == Qt::Horizontal ){
            if( pageHeight > pageWidth ){
                double com = pageHeight;
                pageHeight = pageWidth;
                pageWidth = com;
            }
        } else {
            if( pageHeight < pageWidth ){
                double com = pageHeight;
                pageHeight = pageWidth;
                pageWidth = com;
            }
        }
        double margin = 10.0;
        double tableWidth =  pageWidth - 2.0 * margin;

        QTextCharFormat headerBlockCharFormat;
        headerBlockCharFormat.setFontCapitalization( QFont::AllUppercase );
        headerBlockCharFormat.setFontWeight( QFont::Bold );

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

        QTextBlockFormat headerWithPBBlockFormat = headerBlockFormat;
        headerWithPBBlockFormat.setPageBreakPolicy( QTextFormat::PageBreak_AlwaysBefore );

        QTextBlockFormat parBlockFormat;

        if( printPriceList ){
            cursor.setBlockFormat( headerWithPBBlockFormat );
            cursor.setBlockCharFormat( headerBlockCharFormat );
            cursor.insertText( m_d->priceList->name() );

            cursor.insertBlock( headerBlockFormat );
            cursor.setBlockCharFormat( headerBlockCharFormat );
            cursor.insertText(QObject::trUtf8("Elenco Prezzi") );

            cursor.insertBlock( parBlockFormat );

            QTextTableFormat tableFormat;
            tableFormat.setCellPadding(5);
            tableFormat.setHeaderRowCount(2);
            tableFormat.setBorderStyle( QTextFrameFormat::BorderStyle_Solid);
            tableFormat.setWidth( QTextLength( QTextLength::FixedLength, tableWidth ) );
            QVector<QTextLength> colWidths;
            if( paperOrientation == Qt::Horizontal ){
                double descColWidth = tableWidth - ( 30.0 + 20.0 + 35.0 * fieldsToPrint.size() );
                colWidths << QTextLength( QTextLength::FixedLength, 30.0 )
                          << QTextLength( QTextLength::FixedLength, descColWidth )
                          << QTextLength( QTextLength::FixedLength, 20.0 );
                for( int i=0; i < fieldsToPrint.size(); ++i ){
                    colWidths << QTextLength( QTextLength::FixedLength, 35.0 );
                }
            } else {
                double descColWidth = tableWidth - ( 25.0 + 15.0 + 30.0 * fieldsToPrint.size() );
                colWidths << QTextLength( QTextLength::FixedLength, 25.0 )
                          << QTextLength( QTextLength::FixedLength, descColWidth )
                          << QTextLength( QTextLength::FixedLength, 15.0 );
                for( int i=0; i < fieldsToPrint.size(); ++i ){
                    colWidths << QTextLength( QTextLength::FixedLength, 30.0 );
                }
            }
            tableFormat.setColumnWidthConstraints( colWidths );
            tableFormat.setHeaderRowCount( 2 );
            cursor.insertTable(1, colWidths.size(), tableFormat);

            m_d->priceList->writeODTOnTable( &cursor, printOption, fieldsToPrint, priceDataSetToPrint );

            cursor.movePosition( QTextCursor::End );
        }

        if( printPriceAP ){
            bool firstAP=true;

            QList<PriceItem *> priceItemList = m_d->priceList->priceItemList();
            for( int i=0; i < priceItemList.size(); ++i ){
                if( (!priceItemList.at(i)->hasChildren()) && (priceItemList.at(i)->associateAP(priceDataSetToPrint)) ){
                    if( firstAP ){
                        if( printPriceList ){
                            // abbiamo stampato già l'elenco prezzi
                            cursor.insertBlock( headerWithPBBlockFormat );
                        } else { //  printData == DataAP
                            // non abbiamo stampato l'elenco prezzi
                            cursor.setBlockFormat( headerWithPBBlockFormat );
                        }
                        cursor.setBlockCharFormat( headerBlockCharFormat );
                        cursor.insertText( m_d->priceList->name() );

                        cursor.insertBlock( headerBlockFormat );
                        cursor.setBlockCharFormat( headerBlockCharFormat );
                        cursor.insertText(QObject::trUtf8("Analisi Prezzi") );

                        cursor.insertBlock( parBlockFormat );

                        firstAP = false;
                    } else {
                        cursor.insertBlock( headerWithPBBlockFormat );
                        cursor.insertText( QString() );
                        cursor.insertBlock( parBlockFormat );
                    }

                    QTextTableCellFormat topLeftFormat;
                    topLeftFormat.setProperty( QTextFormatUserDefined::TableCellBorderLeftStyle, QVariant(QTextFrameFormat::BorderStyle_Solid) );
                    topLeftFormat.setProperty( QTextFormatUserDefined::TableCellBorderLeftWidth, QVariant(borderWidth) );
                    topLeftFormat.setProperty( QTextFormatUserDefined::TableCellBorderTopStyle, QVariant(QTextFrameFormat::BorderStyle_Solid) );
                    topLeftFormat.setProperty( QTextFormatUserDefined::TableCellBorderTopWidth, QVariant(borderWidth) );
                    QTextTableCellFormat topRightFormat;
                    topRightFormat.setProperty( QTextFormatUserDefined::TableCellBorderRightStyle, QVariant(QTextFrameFormat::BorderStyle_Solid) );
                    topRightFormat.setProperty( QTextFormatUserDefined::TableCellBorderRightWidth, QVariant(borderWidth) );
                    topRightFormat.setProperty( QTextFormatUserDefined::TableCellBorderTopStyle, QVariant(QTextFrameFormat::BorderStyle_Solid) );
                    topRightFormat.setProperty( QTextFormatUserDefined::TableCellBorderTopWidth, QVariant(borderWidth) );
                    QTextTableCellFormat bottomFormat;
                    bottomFormat.setProperty( QTextFormatUserDefined::TableCellBorderLeftStyle, QVariant(QTextFrameFormat::BorderStyle_Solid) );
                    bottomFormat.setProperty( QTextFormatUserDefined::TableCellBorderLeftWidth, QVariant(borderWidth) );
                    bottomFormat.setProperty( QTextFormatUserDefined::TableCellBorderRightStyle, QVariant(QTextFrameFormat::BorderStyle_Solid) );
                    bottomFormat.setProperty( QTextFormatUserDefined::TableCellBorderRightWidth, QVariant(borderWidth) );
                    bottomFormat.setProperty( QTextFormatUserDefined::TableCellBorderBottomStyle, QVariant(QTextFrameFormat::BorderStyle_Solid) );
                    bottomFormat.setProperty( QTextFormatUserDefined::TableCellBorderBottomWidth, QVariant(borderWidth) );

                    // tabella con informazioni generali sul prezzo
                    // descrizione, codice, etc
                    QTextTableFormat tableFormat;
                    tableFormat.setCellPadding(5);
                    tableFormat.setBorderStyle( QTextFrameFormat::BorderStyle_Solid);
                    tableFormat.setWidth( QTextLength( QTextLength::FixedLength, tableWidth ) );
                    QVector<QTextLength> colWidths;
                    colWidths << QTextLength( QTextLength::FixedLength, 25 )
                              << QTextLength( QTextLength::FixedLength, pageWidth-2.0*margin - 25 );
                    tableFormat.setColumnWidthConstraints( colWidths );
                    QTextTable * table = cursor.insertTable(1, colWidths.size(), tableFormat);

                    table->cellAt( cursor ).setFormat( topLeftFormat );
                    cursor.insertText( priceItemList.at(i)->codeFull() );

                    cursor.movePosition(QTextCursor::NextCell);
                    table->cellAt( cursor ).setFormat( topRightFormat );
                    cursor.insertText( priceItemList.at(i)->shortDescriptionFull() );

                    table->appendRows(1);
                    table->mergeCells( 1, 0, 1, 2 );
                    cursor.movePosition(QTextCursor::PreviousRow );
                    cursor.movePosition(QTextCursor::NextCell );
                    table->cellAt( cursor ).setFormat( bottomFormat );
                    cursor.insertText( priceItemList.at(i)->longDescriptionFull() );
                    cursor.movePosition( QTextCursor::End );

                    // tabella con l'analisi prezzi vera e propria
                    tableFormat.setCellPadding(5);
                    tableFormat.setHeaderRowCount(2);
                    tableFormat.setBorderStyle( QTextFrameFormat::BorderStyle_Solid);
                    tableFormat.setWidth( QTextLength( QTextLength::FixedLength, tableWidth ) );
                    colWidths.clear();
                    if( paperOrientation == Qt::Horizontal ){
                        if( fieldsToPrint.size() > 0 ){
                            colWidths << QTextLength( QTextLength::FixedLength, 10.0 )
                                      << QTextLength( QTextLength::FixedLength, 30.0 )
                                      << QTextLength( QTextLength::FixedLength, 70.0 )
                                      << QTextLength( QTextLength::FixedLength, 20.0 );
                            double usedWidth =  10.0 + 30.0 + 70.0 + 20.0;
                            double colEqualWidth = (tableWidth - usedWidth ) / (1 + 2*fieldsToPrint.size() );
                            for( int i=0; i < (1 + 2*fieldsToPrint.size() ); ++i ){
                                colWidths << QTextLength( QTextLength::FixedLength, colEqualWidth );
                            }
                        } else { // fieldsToPrint.size() == 0
                            if( fieldsToPrint.size() > 1  ){
                                double descWidth = tableWidth - (10.0 + 30.0 + 20.0 + 30.0);
                                colWidths << QTextLength( QTextLength::FixedLength, 10.0 )
                                          << QTextLength( QTextLength::FixedLength, 30.0 )
                                          << QTextLength( QTextLength::FixedLength, descWidth )
                                          << QTextLength( QTextLength::FixedLength, 20.0 )
                                          << QTextLength( QTextLength::FixedLength, 30.0 );
                            }
                        }
                    } else {
                        if( fieldsToPrint.size() > 0 ){
                            double usedWidth = 0.0;
                            if( fieldsToPrint.size() > 1  ){
                                colWidths << QTextLength( QTextLength::FixedLength, 10.0 )
                                          << QTextLength( QTextLength::FixedLength, 20.0 )
                                          << QTextLength( QTextLength::FixedLength, 45.0 )
                                          << QTextLength( QTextLength::FixedLength, 15.0 );
                                usedWidth =  10.0 + 20.0 + 45.0 + 15.0;
                            } else { // fieldsToPrint.size() == 1
                                colWidths << QTextLength( QTextLength::FixedLength, 10.0 )
                                          << QTextLength( QTextLength::FixedLength, 25.0 )
                                          << QTextLength( QTextLength::FixedLength, 65.0 )
                                          << QTextLength( QTextLength::FixedLength, 15.0 );
                                usedWidth =  10.0 + 25.0 + 65.0 + 15.0;
                            }
                            double colEqualWidth = (tableWidth - usedWidth ) / (1 + 2*fieldsToPrint.size() );
                            for( int i=0; i < (1 + 2*fieldsToPrint.size() ); ++i ){
                                colWidths << QTextLength( QTextLength::FixedLength, colEqualWidth );
                            }
                        } else { // fieldsToPrint.size() == 0
                            if( fieldsToPrint.size() > 1  ){
                                double descWidth = tableWidth - (10.0 + 30.0 + 20.0 + 30.0);
                                colWidths << QTextLength( QTextLength::FixedLength, 10.0 )
                                          << QTextLength( QTextLength::FixedLength, 30.0 )
                                          << QTextLength( QTextLength::FixedLength, descWidth )
                                          << QTextLength( QTextLength::FixedLength, 20.0 )
                                          << QTextLength( QTextLength::FixedLength, 30.0 );
                            }
                        }
                    }
                    tableFormat.setColumnWidthConstraints( colWidths );
                    tableFormat.setHeaderRowCount( 2 );
                    cursor.insertTable(1, colWidths.size(), tableFormat);

                    BillPrinter::PrintBillItemsOption billPrItemsOption = BillPrinter::PrintShortDesc;
                    if( printOption == PriceListPrinter::PrintShortDesc ){
                        billPrItemsOption = BillPrinter::PrintShortDesc;
                    } else if( printOption == PriceListPrinter::PrintLongDesc ){
                        billPrItemsOption = BillPrinter::PrintLongDesc;
                    } else if( printOption == PriceListPrinter::PrintShortLongDesc ){
                        billPrItemsOption = BillPrinter::PrintShortLongDesc;
                    } else if( printOption == PriceListPrinter::PrintShortLongDescOpt ){
                        billPrItemsOption = BillPrinter::PrintShortLongDescOpt;
                    }
                    priceItemList.at(i)->associatedAP(priceDataSetToPrint)->writeODTBillOnTable( &cursor, billPrItemsOption, fieldsToPrint, APgroupPrAm );

                    cursor.movePosition( QTextCursor::End );
                }

            }
        }

        QFile *file = new QFile(fileName);
        QString suf = QFileInfo(file->fileName()).suffix().toLower().toLatin1();
        if (suf == "odf" || suf == "opendocumentformat" || suf == "odt") {
            OdtWriter writer(doc, file);
            writer.setPageSizeMM( pageWidth, pageHeight );
            writer.setMarginsMM( margin, margin, margin, margin );
            writer.setPageOrientation( paperOrientation );
            // writer.setCodec(codec);
            return writer.writeAll();
        }
    }
    return false;
}
/** "Help message" or "About" dialog box */
HelpMessageDialog::HelpMessageDialog(QWidget *parent, bool about) :
    QDialog(parent),
    ui(new Ui::HelpMessageDialog)
{
    ui->setupUi(this);
    GUIUtil::restoreWindowGeometry("nHelpMessageDialogWindow", this->size(), this);

    QString version = tr("Unobtanium Core") + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion());
    /* On x86 add a bit specifier to the version so that users can distinguish between
     * 32 and 64 bit builds. On other architectures, 32/64 bit may be more ambigious.
     */
#if defined(__x86_64__)
    version += " " + tr("(%1-bit)").arg(64);
#elif defined(__i386__ )
    version += " " + tr("(%1-bit)").arg(32);
#endif

    if (about)
    {
        setWindowTitle(tr("About Unobtanium Core"));

        /// HTML-format the license message from the core
        QString licenseInfo = QString::fromStdString(LicenseInfo());
        QString licenseInfoHTML = licenseInfo;
        // Make URLs clickable
        QRegExp uri("<(.*)>", Qt::CaseSensitive, QRegExp::RegExp2);
        uri.setMinimal(true); // use non-greedy matching
        licenseInfoHTML.replace(uri, "<a href=\"\\1\">\\1</a>");
        // Replace newlines with HTML breaks
        licenseInfoHTML.replace("\n\n", "<br><br>");

        ui->aboutMessage->setTextFormat(Qt::RichText);
        ui->scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
        text = version + "\n" + licenseInfo;
        ui->aboutMessage->setText(version + "<br><br>" + licenseInfoHTML);
        ui->aboutMessage->setWordWrap(true);
        ui->helpMessage->setVisible(false);
    } else {
        setWindowTitle(tr("Command-line options"));
        QTextCursor cursor(ui->helpMessage->document());
        cursor.insertText(version);
        cursor.insertBlock();
        cursor.insertText(tr("Usage:") + '\n' +
            "  bitcoin-qt [" + tr("command-line options") + "]\n");

        cursor.insertBlock();
        QTextTableFormat tf;
        tf.setBorderStyle(QTextFrameFormat::BorderStyle_None);
        tf.setCellPadding(2);
        QVector<QTextLength> widths;
        widths << QTextLength(QTextLength::PercentageLength, 35);
        widths << QTextLength(QTextLength::PercentageLength, 65);
        tf.setColumnWidthConstraints(widths);
        QTextTable *table = cursor.insertTable(2, 2, tf);

        QString coreOptions = QString::fromStdString(HelpMessage(HMM_BITCOIN_QT));
        bool first = true;
        QTextCharFormat bold;
        bold.setFontWeight(QFont::Bold);
        // note that coreOptions is not translated.
        foreach (const QString &line, coreOptions.split('\n')) {
            if (!first) {
                table->appendRows(1);
                cursor.movePosition(QTextCursor::NextRow);
            }
            first = false;

            if (line.startsWith("  ")) {
                int index = line.indexOf(' ', 3);
                if (index > 0) {
                    cursor.insertText(line.left(index).trimmed());
                    cursor.movePosition(QTextCursor::NextCell);
                    cursor.insertText(line.mid(index).trimmed());
                    continue;
                }
            }
            cursor.movePosition(QTextCursor::NextCell, QTextCursor::KeepAnchor);
            table->mergeCells(cursor);
            cursor.insertText(line.trimmed(), bold);
        }

        table->appendRows(6);
        cursor.movePosition(QTextCursor::NextRow);
        cursor.insertText(tr("UI options") + ":", bold);
        cursor.movePosition(QTextCursor::NextRow);
        if (GetBoolArg("-help-debug", false)) {
            cursor.insertText("-allowselfsignedrootcertificates");
            cursor.movePosition(QTextCursor::NextCell);
            cursor.insertText(tr("Allow self signed root certificates (default: 0)"));
            cursor.movePosition(QTextCursor::NextCell);
        }
        cursor.insertText("-choosedatadir");
        cursor.movePosition(QTextCursor::NextCell);
        cursor.insertText(tr("Choose data directory on startup (default: 0)"));
        cursor.movePosition(QTextCursor::NextCell);
        cursor.insertText("-lang=<lang>");
        cursor.movePosition(QTextCursor::NextCell);
        cursor.insertText(tr("Set language, for example \"de_DE\" (default: system locale)"));
        cursor.movePosition(QTextCursor::NextCell);
        cursor.insertText("-min");
        cursor.movePosition(QTextCursor::NextCell);
        cursor.insertText(tr("Start minimized"));
        cursor.movePosition(QTextCursor::NextCell);
        cursor.insertText("-rootcertificates=<file>");
        cursor.movePosition(QTextCursor::NextCell);
        cursor.insertText(tr("Set SSL root certificates for payment request (default: -system-)"));
        cursor.movePosition(QTextCursor::NextCell);
        cursor.insertText("-splash");
        cursor.movePosition(QTextCursor::NextCell);
        cursor.insertText(tr("Show splash screen on startup (default: 1)"));

        ui->helpMessage->moveCursor(QTextCursor::Start);
        ui->scrollArea->setVisible(false);
        ui->aboutLogo->setVisible(false);
    }
}
Exemple #10
0
bool KoReportODTRenderer::render(const KoReportRendererContext& context, ORODocument* document, int /*page*/)
{
    QTextTableFormat tableFormat;
    tableFormat.setCellPadding(5);
    tableFormat.setHeaderRowCount(1);
    tableFormat.setBorderStyle(QTextFrameFormat::BorderStyle_Solid);
    tableFormat.setWidth(QTextLength(QTextLength::PercentageLength, 100));
    QTextTable *table = m_cursor.insertTable(1, 1, tableFormat);

    long renderedSections = 0;

    for (long s = 0; s < document->sections(); s++) {
        OROSection *section = document->section(s);
        section->sortPrimatives(OROSection::SortX);

        if (section->type() == KRSectionData::GroupHeader || section->type() == KRSectionData::GroupFooter ||
            section->type() == KRSectionData::ReportHeader || section->type() == KRSectionData::ReportFooter ||
            section->type() == KRSectionData::Detail){
            //Add this section to the document

            //Resize the table to accommodate all the primitives in the section
            if (table->columns() < section->primitives()) {
                table->appendColumns(section->primitives() - table->columns());
            }

            if (renderedSections > 0) {
                //We need to back a row, then forward a row to get at the start cell
                m_cursor.movePosition(QTextCursor::PreviousRow);
                m_cursor.movePosition(QTextCursor::NextRow);
            } else {
                //On the first row, ensure we are in the first cell after expanding the table
                while (m_cursor.movePosition(QTextCursor::PreviousCell)){}
            }
            //Render the objects in each section
            for (int i = 0; i < section->primitives(); i++) {
                //Colour the cell using hte section background colour
                OROPrimitive * prim = section->primitive(i);
                QTextTableCell cell = table->cellAt(m_cursor);
                QTextCharFormat format = cell.format();
                format.setBackground(section->backgroundColor());
                cell.setFormat(format);

                if (prim->type() == OROTextBox::TextBox) {
                    OROTextBox * tb = (OROTextBox*) prim;
                    m_cursor.insertText(tb->text());
                } else if (prim->type() == OROImage::Image) {
                    OROImage * im = (OROImage*) prim;

                    m_cursor.insertImage(im->image().scaled(im->size().width(), im->size().height(), Qt::KeepAspectRatio));

                } else if (prim->type() == OROPicture::Picture) {
                    OROPicture * im = (OROPicture*) prim;

                    QImage image(im->size().toSize(), QImage::Format_RGB32);
                    QPainter painter(&image);
                    im->picture()->play(&painter);


                    m_cursor.insertImage(image);
                } else {
                    kWarning() << "unhandled primitive type";
                }
                m_cursor.movePosition(QTextCursor::NextCell);

            }
            if (s < document->sections() - 1) {
                table->appendRows(1);
            }

            renderedSections++;
        }
    }

    QTextDocumentWriter writer(context.destinationUrl.toLocalFile());
    return writer.write(m_document);
}
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;
}
QTextTable * PrintDialog::insertCategoryTable(QTextCursor & cursor, const QString & categoryName)
{
	QTextBlockFormat blockCategoryTitleFormat;
	blockCategoryTitleFormat.setAlignment(Qt::AlignCenter);
	blockCategoryTitleFormat.setTopMargin(40.0);
	blockCategoryTitleFormat.setBottomMargin(30.0);

	QTextCharFormat categoryTitleFormat;
	categoryTitleFormat.setFontCapitalization(QFont::AllUppercase);
	categoryTitleFormat.setFontWeight(25);
	categoryTitleFormat.setFontPointSize(14.0);
	QString category = "Category \"";
	category += categoryName;
	category += "\"";

	cursor.insertBlock(blockCategoryTitleFormat);
	cursor.insertText(category,categoryTitleFormat);


	cursor.insertBlock(QTextBlockFormat()); // to break the previous block format
	QTextTable * table = cursor.insertTable(1, 4);
	if(!table)
		return NULL;
	QTextTableFormat categoryTableFormat;
	categoryTableFormat.setAlignment(Qt::AlignHCenter);
	categoryTableFormat.setHeaderRowCount(1); // header line
	categoryTableFormat.setBorderStyle(QTextTableFormat::BorderStyle_Solid);
	categoryTableFormat.setBorder(1.0);
	categoryTableFormat.setCellPadding(10);
	categoryTableFormat.setCellSpacing(0);

	table->setFormat(categoryTableFormat);

	// header :
	// header cell format :
	QTextCharFormat headerCellFormat;
	headerCellFormat.setFontWeight(50);
	headerCellFormat.setFontPointSize(12.0);
	headerCellFormat.setBackground(QBrush(QColor(60,60,60)));
	headerCellFormat.setForeground(QBrush(QColor(255,255,255)));

	QTextTableCell cell = table->cellAt(0,0);
	cell.setFormat(headerCellFormat);
	cursor = cell.firstCursorPosition();
	cursor.insertText(tr("Position"));

	cell = table->cellAt(0,1);
	cell.setFormat(headerCellFormat);
	cursor = cell.firstCursorPosition();
	cursor.insertText(tr("LastName"));

	cell = table->cellAt(0,2);
	cell.setFormat(headerCellFormat);
	cursor = cell.firstCursorPosition();
	cursor.insertText(tr("Firstname"));

	cell = table->cellAt(0,3);
	cell.setFormat(headerCellFormat);
	cursor = cell.firstCursorPosition();
	cursor.insertText(tr("Time"));

	return table;
}
Exemple #13
0
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);
}
Exemple #14
0
void CalcFrame::printCalc()
{
    const auto milkReception = m_mainWindow->database()->milkReception();

        if (!milkReception) {
            Utils::Main::showMsgIfDbNotChoosed(this);
            return;
        }
        DataWorker dw(m_mainWindow->database());
        try {
            dw.loadMilkReceptions(getWhereQuery());
        } catch (const QString &err) {
            QMessageBox::critical(this, tr("Расчеты"), tr("Произошла ошибка во время подгрузки данных: ") + err);
        }
        const auto deliverers = dw.getDeliverers().values();

        if (deliverers.isEmpty())
        {
            QMessageBox::information(this, tr("Печать"), tr("Отсутствуют данные для печати"));
            return;
        }

        const char f = 'f';
        int row = 0;
        const auto settings = m_mainWindow->getSettings();
        const auto printColumns = m_mainWindow->getSettings()->getPrint().columns;

        QStringList columns;
        for (int i = 0; i < printColumns.size(); ++i) {
            const auto &col = printColumns[i];
            if (col.isShow)
                columns.append(printColumns[i].display);
        }

        const int columnsCount = columns.size();
        if (columnsCount <= 0) {
            QMessageBox::information(this, tr("Печать сдачи молока"), tr("Не выбрана ни одна колонка для печати"));
            return;
        }

        const Settings::Column snCol = printColumns[Constants::PrintColumns::SerialNumber],
                delivNameCol = printColumns[Constants::PrintColumns::DeliverersName],
                litersCol = printColumns[Constants::PrintColumns::Liters],
                fatCol = printColumns[Constants::PrintColumns::Fat],
                proteinCol = printColumns[Constants::PrintColumns::Protein],
                fatUnitsCol = printColumns[Constants::PrintColumns::FatUnits],
                rankWeightCol = printColumns[Constants::PrintColumns::RankWeight],
                payCol = printColumns[Constants::PrintColumns::PayWithOutPrem],
                permiumCol = printColumns[Constants::PrintColumns::Premium],
                sumCol = printColumns[Constants::PrintColumns::Sum],
                signCol = printColumns[Constants::PrintColumns::Sign];

        auto itemToPrintRow = [&](const QString &delivName, const CalculatedItem::Data &item,
                const int rowPos = -1) -> QStringList
        {
            QStringList row;

            if (snCol.isShow)
                row.append(rowPos >= 0 ? QString::number(rowPos) : QString());
            if (delivNameCol.isShow)
                row.append(delivName);
            if (litersCol.isShow)
                row.append(QString::number(item.liters, f, litersCol.prec));
            if (fatCol.isShow)
                row.append(QString::number(item.fat, f, fatCol.prec));
            if (proteinCol.isShow)
                row.append(QString::number(item.protein, f, proteinCol.prec));
            if (fatUnitsCol.isShow)
                row.append(QString::number(item.fatUnits, f, fatCol.prec));
            if (rankWeightCol.isShow)
                row.append(QString::number(item.rankWeight, f, rankWeightCol.prec));
            if (payCol.isShow)
                row.append(QString::number(item.paymentWithOutPremium, f, payCol.prec));
            if (permiumCol.isShow)
                row.append(QString::number(item.premiumForFat, f, permiumCol.prec));
            if (sumCol.isShow)
                row.append(QString::number(floor(item.sum), f, sumCol.prec));
            if (signCol.isShow)
                row.append(QString());

            return row;
        };

        const auto &printSettings = settings->getPrint();

        QTextTableFormat tableFormat;
        tableFormat.setBorder(printSettings.tableBorderWidth);
        tableFormat.setBorderStyle(static_cast<QTextFrameFormat::BorderStyle>(printSettings.tableBorderStyle));
        tableFormat.setColumns(columnsCount);
        tableFormat.setAlignment(Qt::AlignHCenter);
        tableFormat.setWidth(QTextLength(QTextLength::VariableLength, 100));
        tableFormat.setBorderBrush(QBrush(printSettings.tableBorderColor));
        tableFormat.setCellSpacing(printSettings.cellSpacing);
        tableFormat.setCellPadding(printSettings.cellPadding);

        PrintTable print(columnsCount, tableFormat);
        {
            auto &textFormat = print.getTableBodyTextFormat();
            textFormat.setFont(printSettings.tableTextFont);
            textFormat.setForeground(QBrush(printSettings.tableTextColor));
        }
        {
            auto &textFormat = print.getTableHeadersFormat();
            textFormat.setFont(printSettings.tableHeaderFont);
            textFormat.setForeground(QBrush(printSettings.tableHeaderColor));
        }
        print.setHeaders(columns);

        CalculatedItem::Data allResult;
        for (const auto &deliverer: deliverers)
        {
            row++;

            const CalculatedItem::Data calcItem = deliverer->getCalculations();
            print.addRow(itemToPrintRow(deliverer->name(), calcItem, row));

            allResult += calcItem;
        }

        int mergeCount = 0;
        auto itemRow = itemToPrintRow("Итого", allResult, row);
        for (int i = 0; i < Constants::PrintColumns::Liters; i++) {
            const auto &col = printColumns[i];
            if (col.isShow)
                mergeCount++;
        }
        QTextCharFormat resultFormat;
        resultFormat.setFont(printSettings.tableResultFont);
        resultFormat.setForeground(QBrush(printSettings.tableResultColor));

        print.addRow(itemRow, resultFormat, mergeCount);

        auto &cursor = print.cursor();

        cursor.setPosition(0);

        QTextFrameFormat topFrameFormat;
        topFrameFormat.setPadding(4);
        cursor.insertFrame(topFrameFormat);

        QTextBlockFormat textBlockFormat;
        textBlockFormat.setBottomMargin(4);
        textBlockFormat.setAlignment(Qt::AlignLeft);

        QTextBlockFormat captionBlockFormat;
        captionBlockFormat.setAlignment(Qt::AlignCenter);
        cursor.setBlockFormat(textBlockFormat);

        QTextCharFormat textCharFormat;
        textCharFormat.setFont(printSettings.textFont);
        QTextCharFormat captionCharFormat;
        captionCharFormat.setFont(printSettings.captionTextFont);
        captionCharFormat.setForeground(QBrush(printSettings.captionColor));

        cursor.insertText(settings->getFirmName(), textCharFormat);
        cursor.insertBlock();

        cursor.setBlockFormat(captionBlockFormat);

        auto dateMin = QDate(), dateMax = QDate();

        if (isCalcByDate()) {
            dateMin = ui->dateEditFilterStart->date();
            dateMax = ui->dateEditFilterEnd->date();
        } else {
            dateMin = milkReception->getMinDeliveryDate();
            dateMax = milkReception->getMaxDeliveryDate();
        }

        const auto s = dateMax == dateMin ? tr("%1 число").arg(dateMin.toString(Constants::defaultDateFormat())) :
                                            tr("период с %1 по %2")
                                            .arg(dateMin.toString(Constants::defaultDateFormat()))
                                            .arg(dateMax.toString(Constants::defaultDateFormat()));

        cursor.insertText(QString(tr("Платежная ведомость №\n"
                                     "за сданное молоко\n"
                                     "за ") + s), captionCharFormat);
        cursor.insertBlock();
        cursor.setBlockFormat(textBlockFormat);

        cursor.insertText(tr("Населенный пункт: ") + m_mainWindow->getCurrentLocalityName(), textCharFormat);
        cursor.insertBlock();
        cursor.insertText(tr("Приемщик молока: ") + settings->getMilkInspector(), textCharFormat);
        cursor.insertBlock();

        cursor.movePosition(QTextCursor::End);

        QTextFrameFormat bottomFrameFormat;
        bottomFrameFormat.setPadding(4);
        cursor.insertFrame(bottomFrameFormat);

        cursor.setBlockFormat(textBlockFormat);

        const auto minMaxPrice = milkReception->getMinMaxPriceLiter(dateMin, dateMax);
        if (minMaxPrice.first > .0 && minMaxPrice.second > .0) {
            const QString minPrice = QString::number(minMaxPrice.first, f, 2),
                maxPrice = QString::number(minMaxPrice.second, f, 2);

            cursor.insertText(tr("Цена: %1").arg(minPrice == maxPrice ? minPrice : QString("%1 - %2")
                                                                        .arg(minPrice).arg(maxPrice)));
            cursor.insertBlock();
        }
        cursor.insertText(tr("Деньги в сумме: "), textCharFormat);
        cursor.insertBlock();
        cursor.insertText(tr("Получил и выдал согласно ведомости приемщик молока______") + settings->getMilkInspector_2(),
                          textCharFormat);
        cursor.insertBlock();
        cursor.insertText(tr("Директор ") + settings->getFirmName(), textCharFormat);

    print.showDialog();
}