Esempio n. 1
0
/*!
    \fn void QTextTable::insertColumns(int index, int columns)

    Inserts a number of \a columns before the column with the specified \a index.

    \sa insertRows(), resize(), removeRows(), removeColumns(), appendRows(), appendColumns()
*/
void QTextTable::insertColumns(int pos, int num)
{
    Q_D(QTextTable);
    if (num <= 0)
        return;

    if (d->dirty)
        d->update();

    if (pos > d->nCols || pos < 0)
        pos = d->nCols;

//     qDebug() << "-------- insertCols" << pos << num;
    QTextDocumentPrivate *p = d->pieceTable;
    QTextFormatCollection *c = p->formatCollection();
    p->beginEditBlock();

    QList<int> extendedSpans;
    for (int i = 0; i < d->nRows; ++i) {
        int cell;
        if (i == d->nRows - 1 && pos == d->nCols) {
            cell = d->fragment_end;
        } else {
            int logicalGridIndexBeforePosition = pos > 0
                                                 ? d->findCellIndex(d->grid[i*d->nCols + pos - 1])
                                                 : -1;

            // Search for the logical insertion point by skipping past cells which are not the first
            // cell in a rowspan. This means any cell for which the logical grid index is
            // less than the logical cell index of the cell before the insertion.
            int logicalGridIndex;
            int gridArrayOffset = i*d->nCols + pos;
            do {
                cell = d->grid[gridArrayOffset];
                logicalGridIndex = d->findCellIndex(cell);
                gridArrayOffset++;
            } while (logicalGridIndex < logicalGridIndexBeforePosition
                     && gridArrayOffset < d->nRows*d->nCols);

            if (logicalGridIndex < logicalGridIndexBeforePosition
                && gridArrayOffset == d->nRows*d->nCols)
                cell = d->fragment_end;
        }

        if (pos > 0 && pos < d->nCols && cell == d->grid[i*d->nCols + pos - 1]) {
            // cell spans the insertion place, extend it
            if (!extendedSpans.contains(cell)) {
                QTextDocumentPrivate::FragmentIterator it(&p->fragmentMap(), cell);
                QTextCharFormat fmt = c->charFormat(it->format);
                fmt.setTableCellColumnSpan(fmt.tableCellColumnSpan() + num);
                p->setCharFormat(it.position(), 1, fmt);
                d->dirty = true;
                extendedSpans << cell;
            }
        } else {
            /* If the next cell is spanned from the row above, we need to find the right position
            to insert to */
            if (i > 0 && pos < d->nCols && cell == d->grid[(i-1) * d->nCols + pos]) {
                int gridIndex = i*d->nCols + pos;
                const int gridEnd = d->nRows * d->nCols - 1;
                while (gridIndex < gridEnd && cell == d->grid[gridIndex]) {
                    ++gridIndex;
                }
                if (gridIndex == gridEnd)
                    cell = d->fragment_end;
                else
                    cell = d->grid[gridIndex];
            }
            QTextDocumentPrivate::FragmentIterator it(&p->fragmentMap(), cell);
            QTextCharFormat fmt = c->charFormat(it->format);
            fmt.setTableCellRowSpan(1);
            fmt.setTableCellColumnSpan(1);
            Q_ASSERT(fmt.objectIndex() == objectIndex());
            int position = it.position();
            int cfmt = p->formatCollection()->indexForFormat(fmt);
            int bfmt = p->formatCollection()->indexForFormat(QTextBlockFormat());
            for (int i = 0; i < num; ++i)
                p->insertBlock(QTextBeginningOfFrame, position, bfmt, cfmt, QTextUndoCommand::MoveCursor);
        }
    }

    QTextTableFormat tfmt = format();
    tfmt.setColumns(tfmt.columns()+num);
    QVector<QTextLength> columnWidths = tfmt.columnWidthConstraints();
    if (! columnWidths.isEmpty()) {
        for (int i = num; i > 0; --i)
            columnWidths.insert(pos, columnWidths[qMax(0, pos-1)]);
    }
    tfmt.setColumnWidthConstraints (columnWidths);
    QTextObject::setFormat(tfmt);

//     qDebug() << "-------- end insertCols" << pos << num;
    p->endEditBlock();
}
Esempio n. 2
0
/** "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) {
Esempio n. 3
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();
}
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());
    }
}
Esempio n. 5
0
void DeckListModel::printDeckListNode(QTextCursor *cursor, InnerDecklistNode *node)
{
    const int totalColumns = settingsCache->getPriceTagFeature() ? 3 : 2;

    if (node->height() == 1) {
        QTextBlockFormat blockFormat;
        QTextCharFormat charFormat;
        charFormat.setFontPointSize(11);
        charFormat.setFontWeight(QFont::Bold);
        cursor->insertBlock(blockFormat, charFormat);
        QString priceStr;
        if (settingsCache->getPriceTagFeature())
            priceStr = QString().sprintf(": $%.2f", node->recursivePrice(true));
                cursor->insertText(QString("%1: %2").arg(node->getVisibleName()).arg(node->recursiveCount(true)).append(priceStr));

        QTextTableFormat tableFormat;
        tableFormat.setCellPadding(0);
        tableFormat.setCellSpacing(0);
        tableFormat.setBorder(0);
                QTextTable *table = cursor->insertTable(node->size() + 1, totalColumns, tableFormat);
        for (int i = 0; i < node->size(); i++) {
            AbstractDecklistCardNode *card = dynamic_cast<AbstractDecklistCardNode *>(node->at(i));

            QTextCharFormat cellCharFormat;
            cellCharFormat.setFontPointSize(9);

            QTextTableCell cell = table->cellAt(i, 0);
            cell.setFormat(cellCharFormat);
            QTextCursor cellCursor = cell.firstCursorPosition();
            cellCursor.insertText(QString("%1 ").arg(card->getNumber()));

            cell = table->cellAt(i, 1);
            cell.setFormat(cellCharFormat);
            cellCursor = cell.firstCursorPosition();
            cellCursor.insertText(card->getName());

            if (settingsCache->getPriceTagFeature()) {
                            cell = table->cellAt(i, 2);
                            cell.setFormat(cellCharFormat);
                            cellCursor = cell.firstCursorPosition();
                            cellCursor.insertText(QString().sprintf("$%.2f ", card->getTotalPrice()));
            }
        }
    } else if (node->height() == 2) {
        QTextBlockFormat blockFormat;
        QTextCharFormat charFormat;
        charFormat.setFontPointSize(14);
        charFormat.setFontWeight(QFont::Bold);

        cursor->insertBlock(blockFormat, charFormat);
        QString priceStr;
        if (settingsCache->getPriceTagFeature())
            priceStr = QString().sprintf(": $%.2f", node->recursivePrice(true));
                cursor->insertText(QString("%1: %2").arg(node->getVisibleName()).arg(node->recursiveCount(true)).append(priceStr));

        QTextTableFormat tableFormat;
        tableFormat.setCellPadding(10);
        tableFormat.setCellSpacing(0);
        tableFormat.setBorder(0);
        QVector<QTextLength> constraints;
        for (int i = 0; i < totalColumns; i++)
            constraints << QTextLength(QTextLength::PercentageLength, 100.0 / totalColumns);
        tableFormat.setColumnWidthConstraints(constraints);

        QTextTable *table = cursor->insertTable(1, totalColumns, tableFormat);
        for (int i = 0; i < node->size(); i++) {
            QTextCursor cellCursor = table->cellAt(0, (i * totalColumns) / node->size()).lastCursorPosition();
            printDeckListNode(&cellCursor, dynamic_cast<InnerDecklistNode *>(node->at(i)));
        }
    }
    cursor->movePosition(QTextCursor::End);
}
void ResWaReport::BuildPeopleServedSection(QTextCursor& cursor)
{
    CalculatePeople();

    cursor.movePosition(QTextCursor::End);
    cursor.insertBlock();
    cursor.insertText("\n\n5) People Served\n", _headerFormat);

    QTextTableFormat tableFormat;
    QVector<QTextLength> constraints;
    constraints << QTextLength(QTextLength::PercentageLength, 40);
    constraints << QTextLength(QTextLength::PercentageLength, 40);
    tableFormat.setColumnWidthConstraints(constraints);

    cursor.insertText("\nA. # of people served by telephone:\n", _headerFormat);
    cursor.insertBlock();
    cursor.movePosition(QTextCursor::End);
    QTextTable *table = cursor.insertTable(2, 2, tableFormat);
    // HEADERS
    TextToCell(table, 0, 0, "All People Directly Served", &_tableTextFormat);
    TextToCell(table, 1, 0, "Children Directly Served", &_tableTextFormat);
    // VALUES
    //JAS Per Rosemary's need to match #2 on report

    TextToCell(table, 0, 1, QString::number(_numDirectAdult), &_tableCellBlue);
    TextToCell(table, 1, 1, QString::number(_numChildByPhone), &_tableCellBlue);

    //TextToCell(table, 0, 1, QString::number(_numByPhone), &_tableCellBlue);
    //TextToCell(table, 1, 1, QString::number(_numChildByPhone), &_tableCellBlue);


    cursor.insertBlock();
    cursor.movePosition(QTextCursor::End);
    cursor.insertText("\n\nB. # of people served by conflict coaching:\n", _headerFormat);
    cursor.insertBlock();
    cursor.movePosition(QTextCursor::End);
    QTextTable *tableB = cursor.insertTable(2, 2, tableFormat);
    // HEADERS
    TextToCell(tableB, 0, 0, "All People Directly Served", &_tableTextFormat);
    TextToCell(tableB, 1, 0, "Children Directly Served", &_tableTextFormat);
    // VALUES
    TextToCell(tableB, 0, 1, QString::number(_numByCoaching), &_tableCellBlue);
    TextToCell(tableB, 1, 1, QString::number(_numChildByCoaching), &_tableCellBlue);

    cursor.insertBlock();
    cursor.movePosition(QTextCursor::End);
    cursor.insertText("\n\nC.# of people served by telephone concilliation:\n", _headerFormat);
    cursor.insertBlock();
    cursor.movePosition(QTextCursor::End);
    QTextTable *tableC = cursor.insertTable(2, 2, tableFormat);
    // HEADERS
    TextToCell(tableC, 0, 0, "All People Directly Served", &_tableTextFormat);
    TextToCell(tableC, 1, 0, "Children Directly Served", &_tableTextFormat);
    // VALUES
    TextToCell(tableC, 0, 1, QString::number(_numByPhoneConcilliation), &_tableCellBlue);
    TextToCell(tableC, 1, 1, QString::number(_numChildByPhoneConcilliation), &_tableCellBlue);

    cursor.insertBlock();
    cursor.movePosition(QTextCursor::End);
    cursor.insertText("\n\nD. # of people served by mediation sessions:\n", _headerFormat);
    cursor.insertBlock();
    cursor.movePosition(QTextCursor::End);
    QTextTable *tableD = cursor.insertTable(2, 2, tableFormat);
    // HEADERS
    TextToCell(tableD, 0, 0, "All People Directly Served", &_tableTextFormat);
    TextToCell(tableD, 1, 0, "Children Directly Served", &_tableTextFormat);
    // VALUES
    TextToCell(tableD, 0, 1, QString::number(_numBySessions), &_tableCellBlue);
    TextToCell(tableD, 1, 1, QString::number(_numChildBySessions), &_tableCellBlue);

    cursor.insertBlock();
    cursor.movePosition(QTextCursor::End);
    cursor.insertText("\n\nE. # of people served by facilliation sessions:\n", _headerFormat);
    cursor.insertBlock();
    cursor.movePosition(QTextCursor::End);
    QTextTable *tableE = cursor.insertTable(2, 2, tableFormat);
    // HEADERS
    TextToCell(tableE, 0, 0, "All People Directly Served", &_tableTextFormat);
    TextToCell(tableE, 1, 0, "Children Directly Served", &_tableTextFormat);
    // VALUES
    TextToCell(tableE, 0, 1, QString::number(_numBySessionFacilliation), &_tableCellBlue);
    TextToCell(tableE, 1, 1, QString::number(_numChildBySessionFacilliation), &_tableCellBlue);

    cursor.insertBlock();
    cursor.movePosition(QTextCursor::End);
    cursor.insertText("\n\nF. # of people INDIRECTLY served by phone, concilliation, mediation, facilliation:\n", _headerFormat);
    cursor.insertBlock();
    cursor.movePosition(QTextCursor::End);
    QTextTable *tableF = cursor.insertTable(2, 2, tableFormat);
    // HEADERS
    TextToCell(tableF, 0, 0, "All People Indirectly Served", &_tableTextFormat);
    TextToCell(tableF, 1, 0, "Children Indirectly Served", &_tableTextFormat);
    // VALUES
    TextToCell(tableF, 0, 1, QString::number(_numIndirectly), &_tableCellBlue);
    TextToCell(tableF, 1, 1, QString::number(_numChildIndirectly), &_tableCellBlue);

    cursor.insertBlock();
    cursor.movePosition(QTextCursor::End);
    cursor.insertText("\n\nG. # of people served by training and in-service:\n", _headerFormat);
    cursor.insertBlock();
    cursor.movePosition(QTextCursor::End);
    QTextTable *tableG = cursor.insertTable(2, 2, tableFormat);
    // HEADERS
    TextToCell(tableG, 0, 0, "All People Directly Served", &_tableTextFormat);
    TextToCell(tableG, 1, 0, "Children Directly Served", &_tableTextFormat);
    // VALUES
    TextToCell(tableG, 0, 1, QString::number(_numByTraining), &_tableCellBlue);
    TextToCell(tableG, 1, 1, QString::number(_numChildByTraining), &_tableCellBlue);

    cursor.insertBlock();
    cursor.movePosition(QTextCursor::End);
    cursor.insertText("\n\nH. # of additional people served:\n", _headerFormat);
    cursor.insertBlock();
    cursor.movePosition(QTextCursor::End);
    QTextTable *tableH = cursor.insertTable(2, 2, tableFormat);
    // HEADERS
    TextToCell(tableH, 0, 0, "All People Directly Served", &_tableTextFormat);
    TextToCell(tableH, 1, 0, "Children Directly Served", &_tableTextFormat);
    // VALUES
    TextToCell(tableH, 0, 1, QString::number(_numAdditionalServed), &_tableCellBlue);
    TextToCell(tableH, 1, 1, QString::number(_numChildAdditionalServed), &_tableCellBlue);
}
Esempio n. 7
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;
}
Esempio n. 8
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;
}
Esempio n. 9
0
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;
}
Esempio n. 10
0
    bool OutputQtDocument::writeTable()
    {
        /*
            start of table
        */
        m_cursor.beginEditBlock();

        m_cursor.insertBlock();
        m_cursor.insertBlock();
        QTextFrame *topFrame = m_cursor.currentFrame();

        QTextTableFormat tableFormat;
        tableFormat.setCellPadding(4);
        tableFormat.setHeaderRowCount(1);
        /* tableFormat.setBorderStyle(
                QTextFrameFormat::BorderStyle_Double); */
        tableFormat.setMargin(2);
        tableFormat.setWidth(QTextLength(
                QTextLength::PercentageLength, 100));

        QTextTable *table = m_cursor.insertTable(
                m_params->height()+2, m_params->width()+5, tableFormat);

        /*
            headers
        */
        m_cursor = table->cellAt(0, 0).firstCursorPosition();
        m_cursor.insertText("i");
        m_cursor = table->cellAt(0, 1).firstCursorPosition();
        m_cursor.insertText(tr("basis"));
        m_cursor = table->cellAt(0, 2).firstCursorPosition();
        m_cursor.insertHtml("C<sub>i</sub> ");
        m_cursor = table->cellAt(0, 3).firstCursorPosition();
        m_cursor.insertText("B");

        for(size_t j=0; j < m_params->width(); j++)
        {
            m_cursor = table->cellAt(0, j+4).firstCursorPosition();
            m_cursor.insertHtml(QString("P<sub>%1</sub> ").arg(j+1));
            /* m_cursor.insertHtml(QString("C<sub>%1</sub> =").arg(j+1));
            if(m_params->variableType(j) == SimplexMethod::VariableArtificial)
                m_cursor.insertText("W");
            else
                m_cursor.insertText(formatDouble(m_params->rowC(j))); */

        }

        m_cursor = table->cellAt(0, m_params->width()+4).firstCursorPosition();
        m_cursor.insertText(QChar(0x0398)); // theta

        /*
            matrix, columnCompareOp, columnB, columnTheta
        */
        for(size_t i=0; i < m_params->height(); i++)
        {
            m_cursor = table->cellAt(i+1, 0).firstCursorPosition();
            m_cursor.insertText(QString("%1").arg(i+1));

            // basis
            m_cursor = table->cellAt(i+1, 1).firstCursorPosition();
            size_t basisColumn = m_params->columnBasis(i);
            m_cursor.insertHtml(QString("P<sub>%1</sub> ").arg(basisColumn+1));

            // basis C
            m_cursor = table->cellAt(i+1, 2).firstCursorPosition();
            if(m_params->variableType(basisColumn) == SimplexMethod::VariableArtificial)
                m_cursor.insertText("W");
            else
                m_cursor.insertText(formatDouble(m_params->rowC(basisColumn)));

            // B
            m_cursor = table->cellAt(i+1, 3).firstCursorPosition();
            m_cursor.insertText(formatDouble(m_params->columnB(i)));

            // matrix
            for(size_t j=0; j < m_params->width(); j++)
            {
                m_cursor = table->cellAt(i+1, j+4).firstCursorPosition();
                m_cursor.insertText(formatDouble(m_params->matrixA(i, j)));
            }

            // theta
            m_cursor = table->cellAt(i+1, m_params->width()+4).firstCursorPosition();
            if(m_params->columnTheta(i) > 0)
                 m_cursor.insertText(formatDouble(m_params->columnTheta(i)));
            else
                 m_cursor.insertText("-");
        }

        /*
            m+1 row
        */
        m_cursor = table->cellAt(m_params->height()+1, 0).firstCursorPosition();
        m_cursor.insertText("m+1");
        m_cursor = table->cellAt(m_params->height()+1, 3).firstCursorPosition();
        m_cursor.insertText(formatDouble(m_params->F()));

        for(size_t j=0; j < m_params->width(); j++)
        {
            m_cursor = table->cellAt(m_params->height()+1, j+4).firstCursorPosition();
            m_cursor.insertText(formatDouble(m_params->rowD(j)));
        }

        /*
            m+2 row (for artificial variables)
        */
        if(m_params->artificialFlag())
        {
            table->appendRows(1);

            m_cursor = table->cellAt(m_params->height()+2, 0).firstCursorPosition();
            m_cursor.insertText("m+2");

            m_cursor = table->cellAt(m_params->height()+2, 3).firstCursorPosition();
            m_cursor.insertText(formatDouble(m_params->WF()));

            for(size_t j=0; j < m_params->width(); j++)
            {
                m_cursor = table->cellAt(m_params->height()+2, j+4).firstCursorPosition();
                m_cursor.insertText(formatDouble(m_params->rowWD(j)));
            }
        }

        /*
            end of table
        */
        m_cursor.endEditBlock();
        m_cursor.setPosition(topFrame->lastPosition());
        return true;
    }
Esempio n. 11
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);
}
Esempio n. 12
0
void HtmlExporter::emitTable( const QTextTable *table )
{
    //qDebug() << "emitTable" << html;
    QTextTableFormat format = table->format();

    html += QLatin1String( "\n<table" );

    if ( format.hasProperty( QTextFormat::FrameBorder ) ) {
        emitAttribute( "border", QString::number( format.border() ) );
    }

    emitFloatStyle( format.position() );
    emitAlignment( format.alignment() );
    emitTextLength( "width", format.width() );

    if ( format.hasProperty( QTextFormat::TableCellSpacing ) ) {
        emitAttribute( "cellspacing", QString::number( format.cellSpacing() ) );
    }
    if ( format.hasProperty( QTextFormat::TableCellPadding ) ) {
        emitAttribute( "cellpadding", QString::number( format.cellPadding() ) );
    }

    QBrush bg = format.background();
    if ( bg != Qt::NoBrush ) {
        emitAttribute( "bgcolor", bg.color().name() );
    }

    html += QLatin1Char( '>' );

    const int rows = table->rows();
    const int columns = table->columns();

    QVector<QTextLength> columnWidths = format.columnWidthConstraints();
    if ( columnWidths.isEmpty() ) {
        columnWidths.resize( columns );
        columnWidths.fill( QTextLength() );
    }
//    Q_ASSERT(columnWidths.count() == columns);

    QVarLengthArray<bool> widthEmittedForColumn( columns );
    for ( int i = 0; i < columns; ++i ) {
        widthEmittedForColumn[i] = false;
    }

    const int headerRowCount = qMin( format.headerRowCount(), rows );
    if ( headerRowCount > 0 ) {
        html += QLatin1String( "<thead>" );
    }

    for ( int row = 0; row < rows; ++row ) {
        html += QLatin1String( "\n<tr>" );

        for ( int col = 0; col < columns; ++col ) {
            const QTextTableCell cell = table->cellAt( row, col );

            // for col/rowspans
            if ( cell.row() != row ) {
                continue;
            }

            if ( cell.column() != col ) {
                continue;
            }

            html += QLatin1String( "\n<td" );

            if ( !widthEmittedForColumn[col] ) {
                emitTextLength( "width", columnWidths.at( col ) );
                widthEmittedForColumn[col] = true;
            }

            if ( cell.columnSpan() > 1 ) {
                emitAttribute( "colspan", QString::number( cell.columnSpan() ) );
            }

            if ( cell.rowSpan() > 1 ) {
                emitAttribute( "rowspan", QString::number( cell.rowSpan() ) );
            }

            const QTextCharFormat cellFormat = cell.format();
            QBrush bg = cellFormat.background();
            if ( bg != Qt::NoBrush ) {
                emitAttribute( "bgcolor", bg.color().name() );
            }

            html += QLatin1Char( '>' );

            emitFrame( cell.begin() );

            html += QLatin1String( "</td>" );
        }

        html += QLatin1String( "</tr>" );
        if ( headerRowCount > 0 && row == headerRowCount - 1 ) {
            html += QLatin1String( "</thead>" );
        }
    }

    html += QLatin1String( "</table>" );
}
KoTableCellStyle KoTextLayoutTableArea::Private::effectiveCellStyle(const QTextTableCell &tableCell)
{
    QTextTableFormat tableFormat = table->format();
    KoTableCellStyle cellStyle(tableCell.format().toTableCellFormat());
    if (documentLayout->styleManager() && table->format().hasProperty(KoTableStyle::TableTemplate)) {
        if (KoTextTableTemplate *tableTemplate = documentLayout->styleManager()->tableTemplate(table->format().intProperty(KoTableStyle::TableTemplate))) {
            //priorities according to ODF 1.2, 16.18 - table:table-template
            if (tableCell.column() == 0 && tableTemplate->firstColumn()
                    && tableFormat.boolProperty(KoTableStyle::UseFirstColumnStyles)) {
                cellStyle = *(documentLayout->styleManager()->tableCellStyle(tableTemplate->firstColumn()));
                return cellStyle;
            }

            if (tableCell.column() == (table->columns() - 1) && tableTemplate->lastColumn()
                    && tableFormat.boolProperty(KoTableStyle::UseLastColumnStyles)) {
                cellStyle = *(documentLayout->styleManager()->tableCellStyle(tableTemplate->lastColumn()));
                return cellStyle;
            }

            if (tableCell.row() == 0 && tableTemplate->firstRow()
                    && tableFormat.boolProperty(KoTableStyle::UseFirstRowStyles)) {
                cellStyle = *(documentLayout->styleManager()->tableCellStyle(tableTemplate->firstRow()));
                return cellStyle;
            }

            if (tableCell.row() == (table->rows() - 1) && tableTemplate->lastRow()
                    && tableFormat.boolProperty(KoTableStyle::UseLastRowStyles)) {
                cellStyle = *(documentLayout->styleManager()->tableCellStyle(tableTemplate->lastRow()));
                return cellStyle;
            }

            if (((tableCell.row() + 1) % 2) == 0 && tableTemplate->evenRows()
                    && tableFormat.boolProperty(KoTableStyle::UseBandingRowStyles)) {
                cellStyle = *(documentLayout->styleManager()->tableCellStyle(tableTemplate->evenRows()));
                return cellStyle;
            }

            if (((tableCell.row() + 1) % 2) != 0 && tableTemplate->oddRows()
                    && tableFormat.boolProperty(KoTableStyle::UseBandingRowStyles)) {
                cellStyle = *(documentLayout->styleManager()->tableCellStyle(tableTemplate->oddRows()));
                return cellStyle;
            }

            if (((tableCell.column() + 1) % 2) == 0 && tableTemplate->evenColumns()
                    && tableFormat.boolProperty(KoTableStyle::UseBandingColumnStyles)) {
                cellStyle = *(documentLayout->styleManager()->tableCellStyle(tableTemplate->evenColumns()));
                return cellStyle;
            }

            if (((tableCell.column() + 1) % 2) != 0 && tableTemplate->oddColumns()
                    && tableFormat.boolProperty(KoTableStyle::UseBandingColumnStyles)) {
                cellStyle = *(documentLayout->styleManager()->tableCellStyle(tableTemplate->oddColumns()));
                return cellStyle;
            }

            if (tableTemplate->body()) {
                cellStyle = *(documentLayout->styleManager()->tableCellStyle(tableTemplate->body()));
            }
        }
    }

    return cellStyle;
}
void KoTextLayoutTableArea::layoutColumns()
{
    QTextTableFormat tableFormat = d->table->format();

    d->columnPositions.resize(d->table->columns() + 1);
    d->columnWidths.resize(d->table->columns() + 1);

    // Table width.
    d->tableWidth = 0;
    qreal parentWidth = right() - left();
    if (tableFormat.width().rawValue() == 0 || tableFormat.alignment() == Qt::AlignJustify) {
        // We got a zero width value or alignment is justify, so use 100% of parent.
        d->tableWidth = parentWidth - tableFormat.leftMargin() - tableFormat.rightMargin();
    } else {
        if (tableFormat.width().type() == QTextLength::FixedLength) {
            // Fixed length value, so use the raw value directly.
            d->tableWidth = tableFormat.width().rawValue();
        } else if (tableFormat.width().type() == QTextLength::PercentageLength) {
            // Percentage length value, so use a percentage of parent width.
            d->tableWidth = tableFormat.width().rawValue() * (parentWidth / 100)
                - tableFormat.leftMargin() - tableFormat.rightMargin();
        } else {
            // Unknown length type, so use 100% of parent.
            d->tableWidth = parentWidth - tableFormat.leftMargin() - tableFormat.rightMargin();
        }
    }

    // Column widths.
    qreal availableWidth = d->tableWidth; // Width available for columns.
    QList<int> fixedWidthColumns; // List of fixed width columns.
    QList<int> relativeWidthColumns; // List of relative width columns.
    qreal relativeWidthSum = 0; // Sum of relative column width values.
    int numNonStyleColumns = 0;
    for (int col = 0; col < d->table->columns(); ++col) {
        KoTableColumnStyle columnStyle = d->carsManager.columnStyle(col);

        if (columnStyle.hasProperty(KoTableColumnStyle::RelativeColumnWidth)) {
            // Relative width specified. Will be handled in the next loop.
            d->columnWidths[col] = 0.0;
            relativeWidthColumns.append(col);
            relativeWidthSum += columnStyle.relativeColumnWidth();
        } else if (columnStyle.hasProperty(KoTableColumnStyle::ColumnWidth)) {
            // Only width specified, so use it.
            d->columnWidths[col] = columnStyle.columnWidth();
            fixedWidthColumns.append(col);
            availableWidth -= columnStyle.columnWidth();
        } else {
            // Neither width nor relative width specified.
            d->columnWidths[col] = 0.0;
            relativeWidthColumns.append(col); // handle it as a relative width column without asking for anything
            ++numNonStyleColumns;
        }
    }

    // Handle the case that the fixed size columns are larger then the defined table width
    if (availableWidth < 0.0) {
        if (tableFormat.width().rawValue() == 0 && fixedWidthColumns.count() > 0) {
            // If not table width was defined then we need to scale down the fixed size columns so they match
            // into the width of the table.
            qreal diff = (-availableWidth) / qreal(fixedWidthColumns.count());
            foreach(int col, fixedWidthColumns) {
                d->columnWidths[col] = qMax(qreal(0.0), d->columnWidths[col] - diff);
            }
        }
Esempio n. 15
0
/*!
    \fn void QTextTable::removeColumns(int index, int columns)

    Removes a number of \a columns starting with the column at the specified
    \a index.

    \sa insertRows(), insertColumns(), removeRows(), resize(), appendRows(), appendColumns()
*/
void QTextTable::removeColumns(int pos, int num)
{
    Q_D(QTextTable);
//     qDebug() << "-------- removeCols" << pos << num;

    if (num <= 0 || pos < 0)
        return;
    if (d->dirty)
        d->update();
    if (pos >= d->nCols)
        return;
    if (pos + num > d->nCols)
        pos = d->nCols - num;

    QTextDocumentPrivate *p = d->pieceTable;
    QTextFormatCollection *collection = p->formatCollection();
    p->beginEditBlock();

    // delete whole table?
    if (pos == 0 && num == d->nCols) {
        const int pos = p->fragmentMap().position(d->fragment_start);
        p->remove(pos, p->fragmentMap().position(d->fragment_end) - pos + 1);
        p->endEditBlock();
        return;
    }

    p->aboutToRemoveCell(cellAt(0, pos).firstPosition(), cellAt(d->nRows - 1, pos + num - 1).lastPosition());

    QList<int> touchedCells;
    for (int r = 0; r < d->nRows; ++r) {
        for (int c = pos; c < pos + num; ++c) {
            int cell = d->grid[r*d->nCols + c];
            QTextDocumentPrivate::FragmentIterator it(&p->fragmentMap(), cell);
            QTextCharFormat fmt = collection->charFormat(it->format);
            int span = fmt.tableCellColumnSpan();
            if (touchedCells.contains(cell) && span <= 1)
                continue;
            touchedCells << cell;

            if (span > 1) {
                fmt.setTableCellColumnSpan(span - 1);
                p->setCharFormat(it.position(), 1, fmt);
            } else {
                // remove cell
                int index = d->cells.indexOf(cell) + 1;
                int f_end = index < d->cells.size() ? d->cells.at(index) : d->fragment_end;
                p->remove(it.position(), p->fragmentMap().position(f_end) - it.position());
            }
        }
    }

    QTextTableFormat tfmt = format();
    tfmt.setColumns(tfmt.columns()-num);
    QVector<QTextLength> columnWidths = tfmt.columnWidthConstraints();
    if (columnWidths.count() > pos) {
        columnWidths.remove(pos, num);
        tfmt.setColumnWidthConstraints (columnWidths);
    }
    QTextObject::setFormat(tfmt);

    p->endEditBlock();
//     qDebug() << "-------- end removeCols" << pos << num;
}
Esempio n. 16
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;
}
Esempio n. 17
0
void ResWaReport::BuildCasesSection(QTextCursor& cursor)
{
    CalculateCasesTable();

    cursor.movePosition(QTextCursor::End);
    cursor.insertBlock();

    QTextTableFormat tableFormat;
    tableFormat.setHeaderRowCount(1);
    QVector<QTextLength> constraints;
    constraints << QTextLength(QTextLength::PercentageLength, 15);
    constraints << QTextLength(QTextLength::PercentageLength, 7);
    constraints << QTextLength(QTextLength::PercentageLength, 7);
    constraints << QTextLength(QTextLength::PercentageLength, 7);
    constraints << QTextLength(QTextLength::PercentageLength, 7);
    constraints << QTextLength(QTextLength::PercentageLength, 7);
    constraints << QTextLength(QTextLength::PercentageLength, 7);
    constraints << QTextLength(QTextLength::PercentageLength, 7);
    constraints << QTextLength(QTextLength::PercentageLength, 7);
    constraints << QTextLength(QTextLength::PercentageLength, 7);
    constraints << QTextLength(QTextLength::PercentageLength, 7);
    constraints << QTextLength(QTextLength::PercentageLength, 7);
    constraints << QTextLength(QTextLength::PercentageLength, 7);
    constraints << QTextLength(QTextLength::PercentageLength, 7);
    tableFormat.setColumnWidthConstraints(constraints);
    QTextTable *table = cursor.insertTable(CasesTableRows, CasesTableCols, tableFormat);
    // HEADERS
    TextToCell(table, CT_TOTAL_CASES_SETTLED, 0, "Cases Settled");
    TextToCell(table, CT_TOTAL_CASES_PERC, 0, "Percentage of Total Cases Settled");
    TextToCell(table, 0, CT_H_PARENTING, "Parenting Plans");
    TextToCell(table, 0, CT_H_DISOLUTION, "Dissolution");
    TextToCell(table, 0, CT_H_FORECLOSURE, "Foreclosure");
    TextToCell(table, 0, CT_H_TENANT, "Tenant Landlord");
    TextToCell(table, 0, CT_H_BUSINESS, "Business");
    TextToCell(table, 0, CT_H_WORKPLACE, "Workplace");
    TextToCell(table, 0, CT_H_NEIGHBOR, "Neighbor");
    TextToCell(table, 0, CT_H_VICTIM, "Victim Offender");
    TextToCell(table, 0, CT_H_PARENT, "Parent Teen");
    TextToCell(table, 0, CT_H_SCHOOL, "School");
    TextToCell(table, 0, CT_H_ELDER, "Elder");
    TextToCell(table, 0, CT_H_OTHER, "Other");
    TextToCell(table, 0, CT_H_TOTAL, "Total");
    // ROW INDICES
    TextToCell(table, CT_SMALL_CLAIMS , 0, "Small Claims Court Cases", nullptr, &_tableIndexDark);
    TextToCell(table, CT_SMALL_CLAIMS_SETTLED, 0, "Small Claims Court Cases Settled", nullptr, &_tableIndexDark);
    TextToCell(table, CT_SMALL_CLAIMS_PERC, 0, "Percentage of Small Claims Cases Settled", nullptr, &_tableIndexDark);
    TextToCell(table, CT_OTHER_DIST_COURT, 0, "Other District Court Cases");
    TextToCell(table, CT_OTHER_DIST_COURT_SETTLED, 0, "Other District Court Cases Settled");
    TextToCell(table, CT_OTHER_DIST_COURT_PERC, 0, "Percentage of District Court Cases Settled");
    TextToCell(table, CT_JUVENIILE_COURT, 0, "Juvenile Court Cases", nullptr, &_tableIndexDark);
    TextToCell(table, CT_JUVENIILE_COURT_SETTLED, 0, "Juvenile Cases Settled", nullptr, &_tableIndexDark);
    TextToCell(table, CT_JUVENIILE_COURT_PERC, 0, "Percentage of Juvenile Cases Settled", nullptr, &_tableIndexDark);
    TextToCell(table, CT_SUPERIOR_COURT, 0, "Superior Court Cases");
    TextToCell(table, CT_SUPERIOR_COURT_SETTLED, 0, "Superior Court Cases Settled");
    TextToCell(table, CT_SUPERIOR_COURT_PERC, 0, "Percentage of Superior Cases Settled");
    TextToCell(table, CT_OTHER_CASES, 0, "Other Cases", nullptr, &_tableIndexDark);
    TextToCell(table, CT_OTHER_CASES_SETTLED, 0, "Other Cases Settled", nullptr, &_tableIndexDark);
    TextToCell(table, CT_OTHER_CASES_PERC, 0, "Percentage of Other Cases Settled", nullptr, &_tableIndexDark);
    TextToCell(table, CT_TOTAL_CASES, 0, "Total Cases");

    // POPULATE CELLS FROM MATRIX
    for (auto row = 1; row < CasesTableRows; ++row)
        for (auto col = 1; col < CasesTableCols; ++col)
            TextToCell(table, row, col, QString::number(_casesTable[row][col]),nullptr, &_tableCellBlue);
}
Esempio n. 18
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);
}
Esempio n. 19
0
void ResWaReport::BuildEvaluationSection(QTextCursor& cursor)
{
    cursor.movePosition(QTextCursor::End);
    cursor.insertBlock();
    cursor.insertText("\n\n8) Evaluations\n", _headerFormat);

    QTextTableFormat tableFormat;
    QVector<QTextLength> constraints;
    constraints << QTextLength(QTextLength::PercentageLength, 33);
    constraints << QTextLength(QTextLength::PercentageLength, 33);
    constraints << QTextLength(QTextLength::PercentageLength, 33);
    tableFormat.setColumnWidthConstraints(constraints);

    // fair
    cursor.insertBlock();
    cursor.movePosition(QTextCursor::End);
    cursor.insertText("\n\n\tMediators fair and impartial?\n", _headerFormat);
    cursor.insertBlock();
    cursor.movePosition(QTextCursor::End);
    QTextTable *table1 = cursor.insertTable(3, 2, tableFormat);
    TextToCell(table1, 0, 0, "Yes", &_tableTextFormat);
    TextToCell(table1, 1, 0, "No", &_tableTextFormat);
    TextToCell(table1, 2, 0, "Somewhat", &_tableTextFormat);
    TextToCell(table1, 0, 1, QString::number(_q1Yes), &_tableCellBlue);
    TextToCell(table1, 1, 1, QString::number(_q1No), &_tableCellBlue);
    TextToCell(table1, 2, 1, QString::number(_q1Somewhat), &_tableCellBlue);

    // improved situation
    cursor.insertBlock();
    cursor.movePosition(QTextCursor::End);
    cursor.insertText("\tSituation Improved By Mediation?\n", _headerFormat);
    cursor.insertBlock();
    cursor.movePosition(QTextCursor::End);
    QTextTable *table2 = cursor.insertTable(3, 2, tableFormat);
    TextToCell(table2, 0, 0, "Yes", &_tableTextFormat);
    TextToCell(table2, 1, 0, "No", &_tableTextFormat);
    TextToCell(table2, 2, 0, "Somewhat", &_tableTextFormat);
    TextToCell(table2, 0, 1, QString::number(_q2Yes), &_tableCellBlue);
    TextToCell(table2, 1, 1, QString::number(_q2No), &_tableCellBlue);
    TextToCell(table2, 2, 1, QString::number(_q2Somewhat), &_tableCellBlue);

    // helped you communicate
    cursor.insertBlock();
    cursor.movePosition(QTextCursor::End);
    cursor.insertText("\tHelped to communicate with other party?\n", _headerFormat);
    cursor.insertBlock();
    cursor.movePosition(QTextCursor::End);
    QTextTable *table3 = cursor.insertTable(3, 2, tableFormat);
    TextToCell(table3, 0, 0, "Yes", &_tableTextFormat);
    TextToCell(table3, 1, 0, "No", &_tableTextFormat);
    TextToCell(table3, 2, 0, "Somewhat", &_tableTextFormat);
    TextToCell(table3, 0, 1, QString::number(_q3Yes), &_tableCellBlue);
    TextToCell(table3, 1, 1, QString::number(_q3No), &_tableCellBlue);
    TextToCell(table3, 2, 1, QString::number(_q3Somewhat), &_tableCellBlue);

    // helped understand other point view
    cursor.insertBlock();
    cursor.movePosition(QTextCursor::End);
    cursor.insertText("\tHelped to better understand the issues?\n", _headerFormat);
    cursor.insertBlock();
    cursor.movePosition(QTextCursor::End);
    QTextTable *table4 = cursor.insertTable(3, 2, tableFormat);
    TextToCell(table4, 0, 0, "Yes", &_tableTextFormat);
    TextToCell(table4, 1, 0, "No", &_tableTextFormat);
    TextToCell(table4, 2, 0, "Somewhat", &_tableTextFormat);
    TextToCell(table4, 0, 1, QString::number(_q4Yes), &_tableCellBlue);
    TextToCell(table4, 1, 1, QString::number(_q4No), &_tableCellBlue);
    TextToCell(table4, 2, 1, QString::number(_q4Somewhat), &_tableCellBlue);

    // Would recommend to someone else
    cursor.insertBlock();
    cursor.movePosition(QTextCursor::End);
    cursor.insertText("\tRecommend mediation to others?\n", _headerFormat);
    cursor.insertBlock();
    cursor.movePosition(QTextCursor::End);
    QTextTable *table5 = cursor.insertTable(3, 2, tableFormat);
    TextToCell(table5, 0, 0, "Yes", &_tableTextFormat);
    TextToCell(table5, 1, 0, "No", &_tableTextFormat);
    TextToCell(table5, 2, 0, "Somewhat", &_tableTextFormat);
    TextToCell(table5, 0, 1, QString::number(_q5Yes), &_tableCellBlue);
    TextToCell(table5, 1, 1, QString::number(_q5No), &_tableCellBlue);
    TextToCell(table5, 2, 1, QString::number(_q5Somewhat), &_tableCellBlue);

    // was agreement reached
    cursor.insertBlock();
    cursor.movePosition(QTextCursor::End);
    cursor.insertText("\tDid you reach an agreement?\n", _headerFormat);
    cursor.insertBlock();
    cursor.movePosition(QTextCursor::End);
    QTextTable *table6 = cursor.insertTable(3, 2, tableFormat);
    TextToCell(table6, 0, 0, "Yes", &_tableTextFormat);
    TextToCell(table6, 1, 0, "No", &_tableTextFormat);
    TextToCell(table6, 2, 0, "Somewhat", &_tableTextFormat);
    TextToCell(table6, 0, 1, QString::number(_q2Yes), &_tableCellBlue);
    TextToCell(table6, 1, 1, QString::number(_q2No), &_tableCellBlue);
    TextToCell(table6, 2, 1, QString::number(_q2Somewhat), &_tableCellBlue);
}
Esempio n. 20
0
/** "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);
    }
}
Esempio n. 21
0
void CDiaryEdit::draw(QTextDocument& doc)
{
    CDiaryEditLock lock(this);
    QFontMetrics fm(QFont(font().family(),10));

    bool hasGeoCaches = false;
    int cnt;
    int w = doc.textWidth();
    int pointSize = ((10 * (w - 2 * ROOT_FRAME_MARGIN)) / (CHAR_PER_LINE *  fm.width("X")));

    if(pointSize == 0) return;

    doc.setUndoRedoEnabled(false);

    QFont f = textEdit->font();
    f.setPointSize(pointSize);
    textEdit->setFont(f);

    QTextCharFormat fmtCharHeading1;
    fmtCharHeading1.setFont(f);
    fmtCharHeading1.setFontWeight(QFont::Black);
    fmtCharHeading1.setFontPointSize(f.pointSize() + 8);

    QTextCharFormat fmtCharHeading2;
    fmtCharHeading2.setFont(f);
    fmtCharHeading2.setFontWeight(QFont::Black);
    fmtCharHeading2.setFontPointSize(f.pointSize() + 4);

    QTextCharFormat fmtCharStandard;
    fmtCharStandard.setFont(f);

    QTextCharFormat fmtCharHeader;
    fmtCharHeader.setFont(f);
    fmtCharHeader.setBackground(Qt::darkBlue);
    fmtCharHeader.setFontWeight(QFont::Bold);
    fmtCharHeader.setForeground(Qt::white);

    QTextBlockFormat fmtBlockStandard;
    fmtBlockStandard.setTopMargin(10);
    fmtBlockStandard.setBottomMargin(10);
    fmtBlockStandard.setAlignment(Qt::AlignJustify);

    QTextFrameFormat fmtFrameStandard;
    fmtFrameStandard.setTopMargin(5);
    fmtFrameStandard.setBottomMargin(5);
    fmtFrameStandard.setWidth(w - 2 * ROOT_FRAME_MARGIN);

    QTextFrameFormat fmtFrameRoot;
    fmtFrameRoot.setTopMargin(ROOT_FRAME_MARGIN);
    fmtFrameRoot.setBottomMargin(ROOT_FRAME_MARGIN);
    fmtFrameRoot.setLeftMargin(ROOT_FRAME_MARGIN);
    fmtFrameRoot.setRightMargin(ROOT_FRAME_MARGIN);

    QTextTableFormat fmtTableStandard;
    fmtTableStandard.setBorder(1);
    fmtTableStandard.setBorderBrush(Qt::black);
    fmtTableStandard.setCellPadding(4);
    fmtTableStandard.setCellSpacing(0);
    fmtTableStandard.setHeaderRowCount(1);
    fmtTableStandard.setTopMargin(10);
    fmtTableStandard.setBottomMargin(20);
    fmtTableStandard.setWidth(w - 2 * ROOT_FRAME_MARGIN);

    QVector<QTextLength> constraints;
    constraints << QTextLength(QTextLength::FixedLength, 32);
    constraints << QTextLength(QTextLength::VariableLength, 50);
    constraints << QTextLength(QTextLength::VariableLength, 100);
    fmtTableStandard.setColumnWidthConstraints(constraints);

    doc.rootFrame()->setFrameFormat(fmtFrameRoot);
    QTextCursor cursor = doc.rootFrame()->firstCursorPosition();

    cursor.insertText(diary.getName(), fmtCharHeading1);
    cursor.setCharFormat(fmtCharStandard);
    cursor.setBlockFormat(fmtBlockStandard);

    diary.diaryFrame = cursor.insertFrame(fmtFrameStandard);
    {
        QTextCursor cursor1(diary.diaryFrame);

        cursor1.setCharFormat(fmtCharStandard);
        cursor1.setBlockFormat(fmtBlockStandard);

        if(diary.getComment().isEmpty())
        {
            cursor1.insertText(tr("Add your own text here..."));
        }
        else
        {
            cursor1.insertHtml(diary.getComment());
        }
        cursor.setPosition(cursor1.position()+1);
    }

    if(!diary.getWpts().isEmpty())
    {
        QList<CWpt*>& wpts = diary.getWpts();
        cursor.insertText(tr("Waypoints"),fmtCharHeading2);

        QTextTable * table = cursor.insertTable(wpts.count()+1, eMax, fmtTableStandard);
        diary.tblWpt = table;
        table->cellAt(0,eSym).setFormat(fmtCharHeader);
        table->cellAt(0,eInfo).setFormat(fmtCharHeader);
        table->cellAt(0,eComment).setFormat(fmtCharHeader);

        table->cellAt(0,eInfo).firstCursorPosition().insertText(tr("Info"));
        table->cellAt(0,eComment).firstCursorPosition().insertText(tr("Comment"));

        cnt = 1;
        qSort(wpts.begin(), wpts.end(), qSortWptLessTime);

        foreach(CWpt * wpt, wpts)
        {

            table->cellAt(cnt,eSym).firstCursorPosition().insertImage(wpt->getIcon().toImage().scaledToWidth(16, Qt::SmoothTransformation));
            table->cellAt(cnt,eInfo).firstCursorPosition().insertText(wpt->getName() + "\n" + wpt->getInfo(), fmtCharStandard);

            QTextCursor c = table->cellAt(cnt,eComment).firstCursorPosition();
            c.setCharFormat(fmtCharStandard);
            c.setBlockFormat(fmtBlockStandard);
            c.insertHtml(wpt->getComment());

            if(wpt->isGeoCache())
            {
                hasGeoCaches = true;
            }
            cnt++;
        }
Esempio n. 22
0
  // TEXTCELL
  void PrinterVisitor::visitTextCellNodeBefore(TextCell *node)
  {
    if( !ignore_ || firstChild_ )
    {
      ++currentTableRow_;
      table_->insertRows( currentTableRow_, 1 );

      // first column
      QTextTableCell tableCell( table_->cellAt( currentTableRow_, 0 ) );
      if( tableCell.isValid() )
      {
        if( !node->ChapterCounterHtml().isNull() )
        {
          QTextCursor cursor( tableCell.firstCursorPosition() );
          cursor.insertFragment( QTextDocumentFragment::fromHtml(
            node->ChapterCounterHtml() ));

        }
      }

      // second column
      tableCell = table_->cellAt( currentTableRow_, 1 );
      if( tableCell.isValid() )
      {
        QTextCursor cursor( tableCell.firstCursorPosition() );

        if( node->isViewExpression() )
        {
          //view expression table
          QTextTableFormat tableFormatExpression;
          tableFormatExpression.setBorder( 0 );
          tableFormatExpression.setColumns( 1 );
          tableFormatExpression.setCellPadding( 5 );
//          tableFormatExpression.setBackground( QColor(235, 235, 220) ); // 180, 180, 180
          tableFormatExpression.setBackground( QColor(235, 0, 0) ); // 180, 180, 180

          QVector<QTextLength> constraints;
          constraints << QTextLength(QTextLength::PercentageLength, 100);
          tableFormatExpression.setColumnWidthConstraints(constraints);

          cursor.insertTable( 1, 1, tableFormatExpression );
          // QMessageBox::information(0,"uu2", node->text());

          QString html = node->textHtml();
          html += "<br><br>";
          cursor.insertFragment( QTextDocumentFragment::fromHtml( html ));
        }
        else
        {
          QString html = node->textHtml();
          html += "<br><br>";
          html.remove( "file:///" );
          QTextDocumentFragment frgmnt;
          printEditor_->document()->setTextWidth(700);
          cursor.insertFragment(QTextDocumentFragment::fromHtml( html ));
          // QMessageBox::information(0, "uu3", node->text());
        }
      }

      if( firstChild_ )
        firstChild_ = false;
    }
  }
Esempio n. 23
0
void KDReports::AutoTableElement::build( ReportBuilder& builder ) const
{
    if( !d->m_tableModel ) {
        return;
    }
    QTextDocument& textDoc = builder.currentDocument();
    QTextCursor& textDocCursor = builder.cursor();
    textDocCursor.beginEditBlock();

    QTextTableFormat tableFormat;
    const int headerRowCount = d->m_horizontalHeaderVisible ? 1 : 0;
    const int headerColumnCount = d->m_verticalHeaderVisible ? 1 : 0;
    tableFormat.setHeaderRowCount( headerRowCount );
    tableFormat.setProperty( KDReports::HeaderColumnsProperty, headerColumnCount );

    tableFormat.setAlignment( textDocCursor.blockFormat().alignment() );
    fillTableFormat( tableFormat, textDocCursor );

    while (d->m_tableModel->canFetchMore(QModelIndex()))
        d->m_tableModel->fetchMore(QModelIndex());

    const int rows = d->m_tableModel->rowCount();
    const int columns = d->m_tableModel->columnCount();

    QTextTable* textTable = textDocCursor.insertTable( rows + headerRowCount,
                                                       columns + headerColumnCount,
                                                       tableFormat );

    QTextCharFormat tableHeaderFormat;
    tableHeaderFormat.setBackground( d->m_headerBackground );
    //qDebug( "rows = %d, columns = %d", textTable->rows(), textTable->columns() );

    if( d->m_horizontalHeaderVisible ) {
        for( int column = 0; column < columns; column++ ) {
            QTextTableCell cell = textTable->cellAt( 0, column + headerColumnCount );
            Q_ASSERT( cell.isValid() );
            cell.setFormat( tableHeaderFormat );
            d->fillCellFromHeaderData( column, Qt::Horizontal, cell, textDoc, textTable, builder );
        }
    }

    if( d->m_verticalHeaderVisible ) {
        for( int row = 0; row < rows; row++ ) {
            QTextTableCell cell = textTable->cellAt( row + headerRowCount, 0 );
            Q_ASSERT( cell.isValid() );
            cell.setFormat( tableHeaderFormat );
            d->fillCellFromHeaderData( row, Qt::Vertical, cell, textDoc, textTable, builder );
        }
    }

    QVector<QBitArray> coveredCells;
    coveredCells.resize(rows);
    for( int row = 0; row < rows; row++ )
        coveredCells[row].resize(columns);

    // The normal data
    for( int row = 0; row < rows; row++ ) {
        for( int column = 0; column < columns; column++ ) {
            if (coveredCells[row].testBit(column))
                continue;
            QTextTableCell cell = textTable->cellAt( row + headerRowCount, column + headerColumnCount );
            Q_ASSERT( cell.isValid() );
            const QSize span = d->fillTableCell( row, column, cell, textDoc, textTable, builder );
            if (span.isValid()) {
                for (int r = row; r < row + span.height() && r < rows; ++r) {
                    for (int c = column; c < column + span.width() && c < columns; ++c) {
                        coveredCells[r].setBit(c);
                    }
                }
            }
        }
    }

    textDocCursor.movePosition( QTextCursor::End );
    textDocCursor.endEditBlock();

    builder.currentDocumentData().registerAutoTable( textTable, this );
}
Esempio n. 24
0
  void PrinterVisitor::visitLatexCellNodeBefore(LatexCell *node)
  {
    if( !ignore_ || firstChild_ )
    {

      ++currentTableRow_;
      table_->insertRows( currentTableRow_, 1 );

      // first column
      QTextTableCell tableCell( table_->cellAt( currentTableRow_, 0 ) );
      if( tableCell.isValid() )
      {
        if( !node->ChapterCounterHtml().isNull() )
        {
          QTextCursor cursor( tableCell.firstCursorPosition() );
          cursor.insertFragment( QTextDocumentFragment::fromHtml(
            node->ChapterCounterHtml() ));
        }
      }

      // second column
      tableCell = table_->cellAt( currentTableRow_, 1 );
      if( tableCell.isValid() )
      {
        QTextCursor cursor( tableCell.firstCursorPosition() );

        // input table
        QTextTableFormat tableFormatInput;
        tableFormatInput.setBorder( 0 );
        tableFormatInput.setMargin( 6 );
        tableFormatInput.setColumns( 1 );
        tableFormatInput.setCellPadding( 8 );
        tableFormatInput.setBackground( QColor(245, 245, 255) ); // 200, 200, 255
        QVector<QTextLength> constraints;
        constraints << QTextLength(QTextLength::PercentageLength, 100);
                tableFormatInput.setColumnWidthConstraints(constraints);
        cursor.insertTable( 1, 1, tableFormatInput );

        QString html = node->textHtml();
        html += "<br>";
        if( !node->isEvaluated() || node->isClosed() )
          html += "<br>";
        cursor.insertFragment( QTextDocumentFragment::fromHtml( html ));

        if( node->isEvaluated() && !node->isClosed() )
        {
          QTextTableFormat tableFormatOutput;
          tableFormatOutput.setBorder( 0 );
          tableFormatOutput.setMargin( 6 );
          tableFormatOutput.setColumns( 1 );
          tableFormatOutput.setCellPadding( 8 );
          QVector<QTextLength> constraints;
          constraints << QTextLength(QTextLength::PercentageLength, 100);
          tableFormatOutput.setColumnWidthConstraints(constraints);

          cursor = tableCell.lastCursorPosition();
          cursor.insertTable( 1, 1, tableFormatOutput );

          QString outputHtml( node->textOutputHtml() );
          outputHtml += "<br><br>";


          outputHtml.remove( "file:///" );
          cursor.insertFragment( QTextDocumentFragment::fromHtml( outputHtml ));
        }

      }

      if( firstChild_ )
        firstChild_ = false;
    }
  }
/** "Help message" or "About" dialog box */
HelpMessageDialog::HelpMessageDialog(QWidget *parent, bool about) :
    QDialog(parent),
    ui(new Ui::HelpMessageDialog)
{
    ui->setupUi(this);

    QString version = tr("CryptoMailCoin 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 CryptoMailCoin 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" +
            "  cryptomailcoin-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_CRYPTOMAILCOIN_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);
    }
}
Esempio n. 26
0
//! [5]
void MainWindow::insertCalendar()
{
    editor->clear();
    QTextCursor cursor = editor->textCursor();
    cursor.beginEditBlock();

    QDate date(selectedDate.year(), selectedDate.month(), 1);
//! [5]

//! [6]
    QTextTableFormat tableFormat;
    tableFormat.setAlignment(Qt::AlignHCenter);
    tableFormat.setBackground(QColor("#e0e0e0"));
    tableFormat.setCellPadding(2);
    tableFormat.setCellSpacing(4);
//! [6] //! [7]
    QVector<QTextLength> constraints;
    constraints << QTextLength(QTextLength::PercentageLength, 14)
                << QTextLength(QTextLength::PercentageLength, 14)
                << QTextLength(QTextLength::PercentageLength, 14)
                << QTextLength(QTextLength::PercentageLength, 14)
                << QTextLength(QTextLength::PercentageLength, 14)
                << QTextLength(QTextLength::PercentageLength, 14)
                << QTextLength(QTextLength::PercentageLength, 14);
    tableFormat.setColumnWidthConstraints(constraints);
//! [7]

//! [8]
    QTextTable *table = cursor.insertTable(1, 7, tableFormat);
//! [8]

//! [9]
    QTextFrame *frame = cursor.currentFrame();
    QTextFrameFormat frameFormat = frame->frameFormat();
    frameFormat.setBorder(1);
    frame->setFrameFormat(frameFormat);
//! [9]

//! [10]
    QTextCharFormat format = cursor.charFormat();
    format.setFontPointSize(fontSize);

    QTextCharFormat boldFormat = format;
    boldFormat.setFontWeight(QFont::Bold);

    QTextCharFormat highlightedFormat = boldFormat;
    highlightedFormat.setBackground(Qt::yellow);
//! [10]

//! [11]
    for (int weekDay = 1; weekDay <= 7; ++weekDay) {
        QTextTableCell cell = table->cellAt(0, weekDay-1);
//! [11] //! [12]
        QTextCursor cellCursor = cell.firstCursorPosition();
        cellCursor.insertText(QString("%1").arg(QDate::longDayName(weekDay)),
                              boldFormat);
    }
//! [12]

//! [13]
    table->insertRows(table->rows(), 1);
//! [13]

    while (date.month() == selectedDate.month()) {
        int weekDay = date.dayOfWeek();
        QTextTableCell cell = table->cellAt(table->rows()-1, weekDay-1);
        QTextCursor cellCursor = cell.firstCursorPosition();

        if (date == QDate::currentDate())
            cellCursor.insertText(QString("%1").arg(date.day()), highlightedFormat);
        else
            cellCursor.insertText(QString("%1").arg(date.day()), format);

        date = date.addDays(1);
        if (weekDay == 7 && date.month() == selectedDate.month())
            table->insertRows(table->rows(), 1);
    }

    cursor.endEditBlock();
//! [14]
    setWindowTitle(tr("Calendar for %1 %2"
        ).arg(QDate::longMonthName(selectedDate.month())
        ).arg(selectedDate.year()));
}
Esempio n. 27
0
MainWindow::MainWindow()
{
    QMenu *fileMenu = new QMenu(tr("&File"));

    QAction *saveAction = fileMenu->addAction(tr("&Save..."));
    saveAction->setShortcut(tr("Ctrl+S"));
    QAction *quitAction = fileMenu->addAction(tr("E&xit"));
    quitAction->setShortcut(tr("Ctrl+Q"));

    QMenu *showMenu = new QMenu(tr("&Show"));

    QAction *showTableAction = showMenu->addAction(tr("&Table"));

    menuBar()->addMenu(fileMenu);
    menuBar()->addMenu(showMenu);

    editor = new QTextEdit();

//! [0] //! [1]
    QTextCursor cursor(editor->textCursor());
//! [0]
    cursor.movePosition(QTextCursor::Start);
//! [1]

    int rows = 11;
    int columns = 4;

//! [2]
    QTextTableFormat tableFormat;
    tableFormat.setBackground(QColor("#e0e0e0"));
    QVector<QTextLength> constraints;
    constraints << QTextLength(QTextLength::PercentageLength, 16);
    constraints << QTextLength(QTextLength::PercentageLength, 28);
    constraints << QTextLength(QTextLength::PercentageLength, 28);
    constraints << QTextLength(QTextLength::PercentageLength, 28);
    tableFormat.setColumnWidthConstraints(constraints);
//! [3]
    QTextTable *table = cursor.insertTable(rows, columns, tableFormat);
//! [2] //! [3]

    int column;
    int row;
    QTextTableCell cell;
    QTextCursor cellCursor;
    
    QTextCharFormat charFormat;
    charFormat.setForeground(Qt::black);

//! [4]
    cell = table->cellAt(0, 0);
    cellCursor = cell.firstCursorPosition();
    cellCursor.insertText(tr("Week"), charFormat);
//! [4]

//! [5]
    for (column = 1; column < columns; ++column) {
        cell = table->cellAt(0, column);
        cellCursor = cell.firstCursorPosition();
        cellCursor.insertText(tr("Team %1").arg(column), charFormat);
    }

    for (row = 1; row < rows; ++row) {
        cell = table->cellAt(row, 0);
        cellCursor = cell.firstCursorPosition();
        cellCursor.insertText(tr("%1").arg(row), charFormat);

        for (column = 1; column < columns; ++column) {
            if ((row-1) % 3 == column-1) {
//! [5] //! [6]
                cell = table->cellAt(row, column);
                QTextCursor cellCursor = cell.firstCursorPosition();
                cellCursor.insertText(tr("On duty"), charFormat);
            }
//! [6] //! [7]
        }
//! [7] //! [8]
    }
//! [8]

    connect(saveAction, SIGNAL(triggered()), this, SLOT(saveFile()));
    connect(quitAction, SIGNAL(triggered()), this, SLOT(close()));
    connect(showTableAction, SIGNAL(triggered()), this, SLOT(showTable()));

    setCentralWidget(editor);
    setWindowTitle(tr("Text Document Tables"));
}
Esempio n. 28
0
  void PrinterVisitor::visitGraphCellNodeBefore(GraphCell *node)
  {
    if( !ignore_ || firstChild_ )
    {

      ++currentTableRow_;
      table_->insertRows( currentTableRow_, 1 );

      // first column
      QTextTableCell tableCell( table_->cellAt( currentTableRow_, 0 ) );
      if( tableCell.isValid() )
      {
        if( !node->ChapterCounterHtml().isNull() )
        {
          QTextCursor cursor( tableCell.firstCursorPosition() );
          cursor.insertFragment( QTextDocumentFragment::fromHtml(
            node->ChapterCounterHtml() ));
        }
      }

      // second column
      tableCell = table_->cellAt( currentTableRow_, 1 );
      if( tableCell.isValid() )
      {
        QTextCursor cursor( tableCell.firstCursorPosition() );

        // input table
        QTextTableFormat tableFormatInput;
        tableFormatInput.setBorder( 0 );
        tableFormatInput.setColumns( 1 );
        tableFormatInput.setCellPadding( 2 );
        tableFormatInput.setBackground( QColor(245, 245, 255) ); // 200, 200, 255
        QVector<QTextLength> constraints;
        constraints << QTextLength(QTextLength::PercentageLength, 100);
                tableFormatInput.setColumnWidthConstraints(constraints);
        cursor.insertTable( 1, 1, tableFormatInput );

        QString html = node->textHtml();
        if( !node->isEvaluated() || node->isClosed() )
          html += "<br />";
        cursor.insertFragment( QTextDocumentFragment::fromHtml( html ));

        if( node->isEvaluated() && !node->isClosed() )
        {
          QTextTableFormat tableFormatOutput;
          tableFormatOutput.setBorder( 0 );
          tableFormatOutput.setColumns( 1 );
          tableFormatOutput.setCellPadding( 2 );
          QVector<QTextLength> constraints;
          constraints << QTextLength(QTextLength::PercentageLength, 100);
          tableFormatOutput.setColumnWidthConstraints(constraints);

          cursor = tableCell.lastCursorPosition();
          cursor.insertTable( 1, 1, tableFormatOutput );

          QString outputHtml( node->textOutputHtml() );

          outputHtml.remove( "file:///" );
          cursor.insertFragment( QTextDocumentFragment::fromHtml( outputHtml ));
        }

      }
      // print the plot
      if (node->mpPlotWindow && node->mpPlotWindow->isVisible()) {
        ++currentTableRow_;
        table_->insertRows( currentTableRow_, 1 );

        // first column
        tableCell = table_->cellAt( currentTableRow_, 1 );
        if( tableCell.isValid() )
        {
          QTextCursor cursor( tableCell.firstCursorPosition() );

          // input table
          QTextTableFormat tableFormatInput;
          tableFormatInput.setBorder( 0 );
          tableFormatInput.setColumns( 1 );
          tableFormatInput.setCellPadding( 2 );
          QVector<QTextLength> constraints;
          constraints << QTextLength(QTextLength::PercentageLength, 100);
                  tableFormatInput.setColumnWidthConstraints(constraints);
          cursor.insertTable( 1, 1, tableFormatInput );

          OMPlot::Plot *pPlot = node->mpPlotWindow->getPlot();
          // calculate height for widht while preserving aspect ratio.
          int width, height;
          if (pPlot->size().width() > 600) {
            width = 600;
            qreal ratio = (double)pPlot->size().height() / pPlot->size().width();
            height = width * qCeil(ratio);
          } else {
            width = pPlot->size().width();
            height = pPlot->size().height();
          }
          // create a pixmap and render the plot on it
          QPixmap plotPixmap(width, height);
          QwtPlotRenderer plotRenderer;
          plotRenderer.renderTo(pPlot, plotPixmap);
          // insert the pixmap to table
          cursor.insertImage(plotPixmap.toImage());
        }
      }

      if( firstChild_ )
        firstChild_ = false;
    }
  }