TextEffect::TextEffect(MainGraphicsView *view, const QString &text, int duration_ms, const QColor &color) : QGraphicsTextItem(text), time_expire(0), view(view) { this->setDefaultTextColor(color); this->time_expire = game_g->getGameTimeTotalMS() + duration_ms; //this->setFont(game_g->getFontStd()); //this->setFont(game_g->getFontSmall()); this->setFont(game_g->getFontScene()); { // centre alignment - see http://www.cesarbs.org/blog/2011/05/30/aligning-text-in-qgraphicstextitem/ this->setTextWidth(this->boundingRect().width()); QTextBlockFormat format; format.setAlignment(Qt::AlignCenter); QTextCursor cursor = this->textCursor(); cursor.select(QTextCursor::Document); cursor.mergeBlockFormat(format); cursor.clearSelection(); this->setTextCursor(cursor); } this->setCacheMode(QGraphicsItem::DeviceCoordinateCache); }
void TextTools::setHalign(QAction* a) { QTextBlockFormat bformat; Qt::Alignment qa = bformat.alignment() & ~Qt::AlignHorizontal_Mask; switch(a->data().toInt()) { case ALIGN_HCENTER: qa |= Qt::AlignHCenter; break; case ALIGN_RIGHT: qa |= Qt::AlignRight; break; case ALIGN_LEFT: qa |= Qt::AlignLeft; break; } bformat.setAlignment(qa); cursor()->mergeBlockFormat(bformat); _textElement->setAlign((_textElement->align() & ~ ALIGN_HMASK) | Align(a->data().toInt())); updateTools(); layoutText(); }
PeopleNode(const QString &filename){ setFlag(ItemIsMovable); setFlag(ItemIsFocusable); setFlag(ItemIsSelectable); setFlag(ItemSendsGeometryChanges); QPixmap pixmap(filename); pixmap = pixmap.scaled(QSize(kPeopleNodeRadius * 2, kPeopleNodeRadius * 2), Qt::KeepAspectRatio, Qt::SmoothTransformation); setPixmap(pixmap); filename_ = filename; nameItem_ = new QGraphicsTextItem(this); nameItem_->setPos(0, 100); nameItem_->setTextWidth(100); nameItem_->setTextInteractionFlags(Qt::TextEditorInteraction); QTextBlockFormat format; format.setAlignment(Qt::AlignHCenter); nameItem_->textCursor().setBlockFormat(format); QString basename = QFileInfo(filename).baseName(); if(basename.endsWith("_cropped")) basename.remove("_cropped"); nameItem_->textCursor().insertText(basename); connectCtrl_ = new PeopleConnectControl; connectCtrl_->setParentItem(this); connectCtrl_->setPos(kPeopleNodeRadius, kPeopleNodeRadius); connectCtrl_->hide(); g_PeopleNodes << this; }
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; }
void visit(QTextBlock &block) const { QTextBlockFormat format = block.blockFormat(); format.setAlignment(alignment); QTextCursor cursor(block); cursor.setBlockFormat(format); }
void DetailsTable::createRSTTAble(SkyObject *obj, const KStarsDateTime &ut, GeoLocation *geo) { clearContents(); QTextCursor cursor = m_Document->rootFrame()->firstCursorPosition(); QString rtValue, stValue; // Rise/Set time values QString azRValue, azSValue; // Rise/Set azimuth values //Prepare time/position variables QTime rt = obj->riseSetTime(ut, geo, true); //true = use rise time dms raz = obj->riseSetTimeAz(ut, geo, true); //true = use rise time //If transit time is before rise time, use transit time for tomorrow QTime tt = obj->transitTime(ut, geo); dms talt = obj->transitAltitude(ut, geo); if(tt < rt) { tt = obj->transitTime(ut.addDays(1), geo); talt = obj->transitAltitude(ut.addDays(1), geo); } //If set time is before rise time, use set time for tomorrow QTime st = obj->riseSetTime(ut, geo, false); //false = use set time dms saz = obj->riseSetTimeAz(ut, geo, false); //false = use set time if(st < rt) { st = obj->riseSetTime(ut.addDays(1), geo, false); //false = use set time saz = obj->riseSetTimeAz(ut.addDays( 1 ), geo, false); //false = use set time } if(rt.isValid()) { rtValue = QString().sprintf("%02d:%02d", rt.hour(), rt.minute()); stValue = QString().sprintf("%02d:%02d", st.hour(), st.minute()); azRValue = raz.toDMSString(); azSValue = saz.toDMSString(); } else { if(obj->alt().Degrees() > 0.0) { rtValue = i18n("Circumpolar"); stValue = i18n("Circumpolar"); } else { rtValue = i18n("Never rises"); stValue = i18n("Never rises"); } azRValue = i18nc("Not Applicable", "N/A"); azSValue = i18nc("Not Applicable", "N/A"); } // Set column width constraints QVector<QTextLength> constraints; constraints << QTextLength(QTextLength::PercentageLength, 25) << QTextLength(QTextLength::PercentageLength, 25) << QTextLength(QTextLength::PercentageLength, 25) << QTextLength(QTextLength::PercentageLength, 25); m_TableFormat.setColumnWidthConstraints(constraints); // Insert table & row containing table name QTextTable *table = cursor.insertTable(4, 4, m_TableFormat); table->mergeCells(0, 0, 1, 4); QTextBlockFormat centered; centered.setAlignment(Qt::AlignCenter); table->cellAt(0, 0).firstCursorPosition().setBlockFormat(centered); table->cellAt(0, 0).firstCursorPosition().insertText(i18n("Rise/Set/Transit"), m_TableTitleCharFormat); // Insert cell names & values table->cellAt(1, 0).firstCursorPosition().insertText(i18n("Rise time:"), m_ItemNameCharFormat); table->cellAt(1, 0).firstCursorPosition().setBlockFormat(centered); table->cellAt(1, 1).firstCursorPosition().insertText(rtValue, m_ItemValueCharFormat); table->cellAt(2, 0).firstCursorPosition().insertText(i18n("Transit time:"), m_ItemNameCharFormat); table->cellAt(2, 0).firstCursorPosition().setBlockFormat(centered); table->cellAt(2, 1).firstCursorPosition().insertText(QString().sprintf("%02d:%02d", tt.hour(), tt.minute()), m_ItemValueCharFormat); table->cellAt(3, 0).firstCursorPosition().insertText(i18n("Set time:"), m_ItemNameCharFormat); table->cellAt(3, 0).firstCursorPosition().setBlockFormat(centered); table->cellAt(3, 1).firstCursorPosition().insertText(stValue, m_ItemValueCharFormat); table->cellAt(1, 2).firstCursorPosition().insertText(i18n("Azimuth at rise:"), m_ItemNameCharFormat); table->cellAt(1, 2).firstCursorPosition().setBlockFormat(centered); table->cellAt(1, 3).firstCursorPosition().insertText(azRValue, m_ItemValueCharFormat); table->cellAt(2, 2).firstCursorPosition().insertText(i18n("Altitude at transit:"), m_ItemNameCharFormat); table->cellAt(2, 2).firstCursorPosition().setBlockFormat(centered); table->cellAt(2, 3).firstCursorPosition().insertText(talt.toDMSString(), m_ItemValueCharFormat); table->cellAt(3, 2).firstCursorPosition().insertText(i18n("Azimuth at set:"), m_ItemNameCharFormat); table->cellAt(3, 2).firstCursorPosition().setBlockFormat(centered); table->cellAt(3, 3).firstCursorPosition().insertText(azSValue, m_ItemValueCharFormat); // Restore the position and other time-dependent parameters obj->recomputeCoords( ut, geo ); }
void DetailsTable::createCoordinatesTable(SkyObject *obj, const KStarsDateTime &ut, GeoLocation *geo) { clearContents(); QTextCursor cursor = m_Document->rootFrame()->firstCursorPosition(); // Set column width constraints QVector<QTextLength> constraints; constraints << QTextLength(QTextLength::PercentageLength, 25) << QTextLength(QTextLength::PercentageLength, 25) << QTextLength(QTextLength::PercentageLength, 25) << QTextLength(QTextLength::PercentageLength, 25); m_TableFormat.setColumnWidthConstraints(constraints); // Insert table & row containing table name QTextTable *table = cursor.insertTable(4, 4, m_TableFormat); table->mergeCells(0, 0, 1, 4); QTextBlockFormat centered; centered.setAlignment(Qt::AlignCenter); table->cellAt(0, 0).firstCursorPosition().setBlockFormat(centered); table->cellAt(0, 0).firstCursorPosition().insertText(i18n("Coordinates"), m_TableTitleCharFormat); //Coordinates Section: //Don't use KLocale::formatNumber() for the epoch string, //because we don't want a thousands-place separator! QString sEpoch = QString::number(ut.epoch(), 'f', 1); //Replace the decimal point with localized decimal symbol sEpoch.replace('.', KGlobal::locale()->decimalSymbol()); table->cellAt(1, 0).firstCursorPosition().insertText(i18n("RA (%1):", sEpoch), m_ItemNameCharFormat); table->cellAt(1, 0).firstCursorPosition().setBlockFormat(centered); table->cellAt(1, 1).firstCursorPosition().insertText(obj->ra().toHMSString(), m_ItemValueCharFormat); table->cellAt(2, 0).firstCursorPosition().insertText(i18n("Dec (%1):", sEpoch), m_ItemNameCharFormat); table->cellAt(2, 0).firstCursorPosition().setBlockFormat(centered); table->cellAt(2, 1).firstCursorPosition().insertText(obj->dec().toDMSString(), m_ItemValueCharFormat); table->cellAt(3, 0).firstCursorPosition().insertText(i18n("Hour angle:"), m_ItemNameCharFormat); table->cellAt(3, 0).firstCursorPosition().setBlockFormat(centered); //Hour Angle can be negative, but dms HMS expressions cannot. //Here's a kludgy workaround: dms lst = geo->GSTtoLST(ut.gst()); dms ha(lst.Degrees() - obj->ra().Degrees()); QChar sgn('+'); if(ha.Hours() > 12.0) { ha.setH(24.0 - ha.Hours()); sgn = '-'; } table->cellAt(3, 1).firstCursorPosition().insertText(QString("%1%2").arg(sgn).arg(ha.toHMSString()), m_ItemValueCharFormat); table->cellAt(1, 2).firstCursorPosition().insertText(i18n("Azimuth:"), m_ItemNameCharFormat); table->cellAt(1, 2).firstCursorPosition().setBlockFormat(centered); table->cellAt(1, 3).firstCursorPosition().insertText(obj->az().toDMSString(), m_ItemValueCharFormat); table->cellAt(2, 2).firstCursorPosition().insertText(i18n("Altitude:"), m_ItemNameCharFormat); table->cellAt(2, 2).firstCursorPosition().setBlockFormat(centered); dms a; if(Options::useAltAz()) { a = obj->alt(); } else { a = obj->altRefracted(); } table->cellAt(2, 3).firstCursorPosition().insertText(a.toDMSString(), m_ItemValueCharFormat); table->cellAt(3, 2).firstCursorPosition().insertText(i18n("Airmass:"), m_ItemNameCharFormat); table->cellAt(3, 2).firstCursorPosition().setBlockFormat(centered); //Airmass is approximated as the secant of the zenith distance, //equivalent to 1./sin(Alt). Beware of Inf at Alt=0! QString aMassStr; if(obj->alt().Degrees() > 0.0) { aMassStr = KGlobal::locale()->formatNumber(1./sin(obj->alt().radians() ), 2); } else { aMassStr = "--"; } table->cellAt(3, 3).firstCursorPosition().insertText(aMassStr, m_ItemValueCharFormat); // Restore the position and other time-dependent parameters obj->recomputeCoords(ut, geo); }
void DetailsTable::createGeneralTable(SkyObject *obj) { clearContents(); QTextCursor cursor = m_Document->rootFrame()->firstCursorPosition(); //Fill in the data fields //Contents depend on type of object StarObject *s = 0; DeepSkyObject *dso = 0; KSPlanetBase *ps = 0; QString pname, oname; QString objNamesVal, objTypeVal, objDistVal, objSizeVal, objMagVal, objBvVal, objIllumVal; QString objSizeLabel, objMagLabel; switch(obj->type()) { case SkyObject::STAR: { s = (StarObject *)obj; objNamesVal = s->longname(); if(s->getHDIndex() != 0) { if(!s->longname().isEmpty()) { objNamesVal = s->longname() + QString(", HD%1").arg(QString::number(s->getHDIndex())) ; } else { objNamesVal = QString(", HD%1").arg(QString::number(s->getHDIndex())); } } objTypeVal = s->sptype() + ' ' + i18n("star"); objMagVal = i18nc("number in magnitudes", "%1 mag", KGlobal::locale()->formatNumber(s->mag(), 1)); //show to tenths place if(s->getBVIndex() < 30.0) { objBvVal = QString::number(s->getBVIndex(), 'g', 2); } //distance if(s->distance() > 2000. || s->distance() < 0.) // parallax < 0.5 mas { objDistVal = i18nc("larger than 2000 parsecs", "> 2000 pc"); } else if(s->distance() > 50.0) //show to nearest integer { objDistVal = i18nc("number in parsecs", "%1 pc", KGlobal::locale()->formatNumber(s->distance(), 0)); } else if(s->distance() > 10.0) //show to tenths place { objDistVal = i18nc("number in parsecs", "%1 pc", KGlobal::locale()->formatNumber(s->distance(), 1)); } else //show to hundredths place { objDistVal = i18nc("number in parsecs", "%1 pc", KGlobal::locale()->formatNumber(s->distance(), 2)); } //Note multiplicity/variablility in angular size label if(s->isMultiple() && s->isVariable()) { objSizeLabel = i18nc("the star is a multiple star", "multiple") + ','; objSizeVal = i18nc("the star is a variable star", "variable"); } else if(s->isMultiple()) { objSizeLabel = i18nc("the star is a multiple star", "multiple"); } else if(s->isVariable()) { objSizeLabel = i18nc("the star is a variable star", "variable"); } objIllumVal = "--"; break; //End of stars case } case SkyObject::ASTEROID: //[fall through to planets] case SkyObject::COMET: //[fall through to planets] case SkyObject::MOON: //[fall through to planets] case SkyObject::PLANET: { ps = (KSPlanetBase *)obj; objNamesVal = ps->longname(); //Type is "G5 star" for Sun if(ps->name() == "Sun") { objTypeVal = i18n("G5 star"); } else if(ps->name() == "Moon") { objTypeVal = ps->translatedName(); } else if(ps->name() == i18n("Pluto") || ps->name() == "Ceres" || ps->name() == "Eris") // TODO: Check if Ceres / Eris have translations and i18n() them { objTypeVal = i18n("Dwarf planet"); } else { objTypeVal = ps->typeName(); } //Magnitude: The moon displays illumination fraction instead if(obj->name() == "Moon") { objIllumVal = QString("%1 %").arg(KGlobal::locale()->formatNumber(((KSMoon *)obj)->illum()*100., 0)); } objMagVal = i18nc("number in magnitudes", "%1 mag", KGlobal::locale()->formatNumber(ps->mag(), 1)); //show to tenths place //Distance from Earth. The moon requires a unit conversion if(ps->name() == "Moon") { objDistVal = i18nc("distance in kilometers", "%1 km", KGlobal::locale()->formatNumber(ps->rearth() * AU_KM )); } else { objDistVal = i18nc("distance in Astronomical Units", "%1 AU", KGlobal::locale()->formatNumber(ps->rearth())); } //Angular size; moon and sun in arcmin, others in arcsec if(ps->angSize()) { if(ps->name() == "Sun" || ps->name() == "Moon") { // Needn't be a plural form because sun / moon will never contract to 1 arcminute objSizeVal = i18nc("angular size in arcminutes", "%1 arcmin", KGlobal::locale()->formatNumber(ps->angSize())); } else { objSizeVal = i18nc("angular size in arcseconds","%1 arcsec", KGlobal::locale()->formatNumber(ps->angSize() * 60.0)); } } else { objSizeVal = "--"; } break; //End of planets/comets/asteroids case } default: //Deep-sky objects { dso = (DeepSkyObject *)obj; //Show all names recorded for the object if(!dso->longname().isEmpty() && dso->longname() != dso->name()) { pname = dso->translatedLongName(); oname = dso->translatedName(); } else { pname = dso->translatedName(); } if(!dso->translatedName2().isEmpty()) { if(oname.isEmpty()) { oname = dso->translatedName2(); } else { oname += ", " + dso->translatedName2(); } } if(dso->ugc() != 0) { if(!oname.isEmpty()) { oname += ", "; } oname += "UGC " + QString::number(dso->ugc()); } if(dso->pgc() != 0) { if(!oname.isEmpty()) { oname += ", "; } oname += "PGC " + QString::number(dso->pgc()); } if(!oname.isEmpty()) { pname += ", " + oname; } objNamesVal = pname; objTypeVal = dso->typeName(); if(dso->type() == SkyObject::RADIO_SOURCE) { objMagLabel = i18nc("integrated flux at a frequency", "Flux(%1):", dso->customCatalog()->fluxFrequency()); objMagVal = i18nc("integrated flux value", "%1 %2", KGlobal::locale()->formatNumber(dso->flux(), 1), dso->customCatalog()->fluxUnit()); //show to tenths place } else if(dso->mag() > 90.0) { objMagVal = "--"; } else { objMagVal = i18nc("number in magnitudes", "%1 mag", KGlobal::locale()->formatNumber(dso->mag(), 1)); //show to tenths place } //No distances at this point... objDistVal = "--"; //Only show decimal place for small angular sizes if(dso->a() > 10.0) { objSizeVal = i18nc("angular size in arcminutes", "%1 arcmin", KGlobal::locale()->formatNumber(dso->a(), 0)); } else if(dso->a()) { objSizeVal = i18nc("angular size in arcminutes", "%1 arcmin", KGlobal::locale()->formatNumber(dso->a(), 1)); } else { objSizeVal = "--"; } break; //End of deep-space objects case } } //Common to all types: if(obj->type() == SkyObject::CONSTELLATION ) { objTypeVal = KStarsData::Instance()->skyComposite()->getConstellationBoundary()->constellationName(obj); } else { objTypeVal = i18nc("%1 type of sky object (planet, asteroid etc), %2 name of a constellation", "%1 in %2", objTypeVal, KStarsData::Instance()->skyComposite()->getConstellationBoundary()->constellationName(obj)); } QVector<QTextLength> constraints; constraints << QTextLength(QTextLength::PercentageLength, 25) << QTextLength(QTextLength::PercentageLength, 25) << QTextLength(QTextLength::PercentageLength, 25) << QTextLength(QTextLength::PercentageLength, 25); m_TableFormat.setColumnWidthConstraints(constraints); QTextTable *table = cursor.insertTable(5, 4, m_TableFormat); table->mergeCells(0, 0, 1, 4); QTextBlockFormat centered; centered.setAlignment(Qt::AlignCenter); table->cellAt(0, 0).firstCursorPosition().setBlockFormat(centered); table->cellAt(0, 0).firstCursorPosition().insertText(i18n("General"), m_TableTitleCharFormat); table->mergeCells(1, 1, 1, 3); table->cellAt(1, 0).firstCursorPosition().insertText(i18n("Names:"), m_ItemNameCharFormat); table->cellAt(1, 0).firstCursorPosition().setBlockFormat(centered); table->cellAt(1, 1).firstCursorPosition().insertText(objNamesVal, m_ItemValueCharFormat); table->cellAt(2, 0).firstCursorPosition().insertText(i18n("Type:"), m_ItemNameCharFormat); table->cellAt(2, 0).firstCursorPosition().setBlockFormat(centered); table->cellAt(2, 1).firstCursorPosition().insertText(objTypeVal, m_ItemValueCharFormat); table->cellAt(3, 0).firstCursorPosition().insertText(i18n("Distance:"), m_ItemNameCharFormat); table->cellAt(3, 0).firstCursorPosition().setBlockFormat(centered); table->cellAt(3, 1).firstCursorPosition().insertText(objDistVal, m_ItemValueCharFormat); table->cellAt(4, 0).firstCursorPosition().insertText(i18n("Size:"), m_ItemNameCharFormat); table->cellAt(4, 0).firstCursorPosition().setBlockFormat(centered); table->cellAt(4, 1).firstCursorPosition().insertText(objSizeVal, m_ItemValueCharFormat); table->cellAt(2, 2).firstCursorPosition().insertText(i18n("Magnitude:"), m_ItemNameCharFormat); table->cellAt(2, 2).firstCursorPosition().setBlockFormat(centered); table->cellAt(2, 3).firstCursorPosition().insertText(objMagVal, m_ItemValueCharFormat); table->cellAt(3, 2).firstCursorPosition().insertText(i18n("B-V index:"), m_ItemNameCharFormat); table->cellAt(3, 2).firstCursorPosition().setBlockFormat(centered); table->cellAt(3, 3).firstCursorPosition().insertText(objBvVal, m_ItemValueCharFormat); table->cellAt(4, 2).firstCursorPosition().insertText(i18n("Illumination:"), m_ItemNameCharFormat); table->cellAt(4, 2).firstCursorPosition().setBlockFormat(centered); table->cellAt(4, 3).firstCursorPosition().insertText(objIllumVal, m_ItemValueCharFormat); }
void TextZone::insertFromMimeData (const QMimeData *source ) { QTextCursor cursor = this->textCursor(); int bottMargin; int textIndent; int leftMargin; Qt::Alignment textAlignment; int textHeight; QString fontFamily; if(cursor.atStart() == true || cursor.position() == 1 || cursor.position() == 0){ int defaultIndex = textStyles->defaultStyleIndex(); bottMargin = textStyles->blockBottomMarginAt(defaultIndex); textIndent = textStyles->blockFirstLineIndentAt(defaultIndex); leftMargin = textStyles->blockLeftMarginAt(defaultIndex); textAlignment = textStyles->blockAlignmentTrueNameAt(defaultIndex); textHeight = textStyles->fontSizeAt(defaultIndex); fontFamily = textStyles->fontFamilyAt(defaultIndex); } else{ bottMargin = cursor.blockFormat().bottomMargin(); textIndent = cursor.blockFormat().textIndent(); leftMargin = cursor.blockFormat().leftMargin(); textAlignment = cursor.blockFormat().alignment(); textHeight = cursor.charFormat().fontPointSize(); fontFamily = cursor.charFormat().fontFamily(); } if(source->hasHtml() && !forceCopyWithoutFormatting){ QByteArray richtext; if (source->hasFormat(QLatin1String("text/rtf"))) { richtext = source->data(QLatin1String("text/rtf")); } else if (source->hasHtml()) { richtext = mimeToRtf(source); } QTextEdit *textEdit = new QTextEdit(0); RTF::Reader reader; QBuffer buffer(&richtext); buffer.open(QIODevice::ReadOnly); reader.read(&buffer, textEdit->textCursor()); buffer.close(); QString sourceString = textEdit->toHtml(); sourceString.remove(QChar::ReplacementCharacter); sourceString.remove(QChar::ObjectReplacementCharacter); sourceString.remove(QChar::Null); //htmlText QTextDocument *document = new QTextDocument; document->setHtml(Utils::parseHtmlText(sourceString)); QTextBlockFormat blockFormat; blockFormat.setBottomMargin(bottMargin); blockFormat.setTextIndent(textIndent); blockFormat.setLeftMargin(leftMargin); blockFormat.setAlignment(textAlignment); blockFormat.setRightMargin(0); QTextCharFormat charFormat; charFormat.setFontPointSize(textHeight); charFormat.setFontFamily(fontFamily); charFormat.setBackground(QBrush(Qt::NoBrush)); charFormat.setForeground(QBrush(Qt::NoBrush)); charFormat.setAnchor(false); charFormat.setUnderlineStyle(QTextCharFormat::NoUnderline); charFormat.setFontStrikeOut(false); QTextCursor *tCursor = new QTextCursor(document); tCursor->movePosition(QTextCursor::Start, QTextCursor::MoveAnchor,1); tCursor->movePosition(QTextCursor::End, QTextCursor::KeepAnchor,1); tCursor->mergeCharFormat(charFormat); tCursor->mergeBlockFormat(blockFormat); QTextCursor cursor = this->textCursor(); cursor.insertHtml(document->toHtml("utf-8")); qDebug() << "insertFromMimeData Html"; } else if(source->hasText() || forceCopyWithoutFormatting){ QTextDocument *document = new QTextDocument; document->setPlainText(qvariant_cast<QString>(source->text())); QTextBlockFormat blockFormat; blockFormat.setBottomMargin(bottMargin); blockFormat.setTextIndent(textIndent); blockFormat.setLeftMargin(leftMargin); blockFormat.setAlignment(textAlignment); blockFormat.setRightMargin(0); QTextCharFormat charFormat; charFormat.setFontPointSize(textHeight); charFormat.setFontFamily(fontFamily); charFormat.clearForeground(); charFormat.setBackground(QBrush(Qt::NoBrush)); charFormat.setForeground(QBrush(Qt::NoBrush)); charFormat.setAnchor(false); charFormat.setUnderlineStyle(QTextCharFormat::NoUnderline); charFormat.setFontStrikeOut(false); QTextCursor *tCursor = new QTextCursor(document); tCursor->movePosition(QTextCursor::Start, QTextCursor::MoveAnchor,1); tCursor->movePosition(QTextCursor::End, QTextCursor::KeepAnchor,1); tCursor->mergeCharFormat(charFormat); tCursor->mergeBlockFormat(blockFormat); QTextCursor cursor = this->textCursor(); cursor.insertHtml(document->toHtml("utf-8")); qDebug() << "insertFromMimeData plainText"; } }
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; }
int main(int argc, char *argv[]) { QApplication app(argc, argv); //! [0] QTextEdit *editor = new QTextEdit(); QTextCursor cursor(editor->textCursor()); //! [0] cursor.movePosition(QTextCursor::Start); QTextBlockFormat blockFormat = cursor.blockFormat(); blockFormat.setTopMargin(4); blockFormat.setLeftMargin(4); blockFormat.setRightMargin(4); blockFormat.setBottomMargin(4); cursor.setBlockFormat(blockFormat); cursor.insertText(tr("This contains plain text inside a " "text block with margins to keep it separate " "from other parts of the document.")); cursor.insertBlock(); //! [1] QTextBlockFormat backgroundFormat = blockFormat; backgroundFormat.setBackground(QColor("lightGray")); cursor.setBlockFormat(backgroundFormat); //! [1] cursor.insertText(tr("The background color of a text block can be " "changed to highlight text.")); cursor.insertBlock(); QTextBlockFormat rightAlignedFormat = blockFormat; rightAlignedFormat.setAlignment(Qt::AlignRight); cursor.setBlockFormat(rightAlignedFormat); cursor.insertText(tr("The alignment of the text within a block is " "controlled by the alignment properties of " "the block itself. This text block is " "right-aligned.")); cursor.insertBlock(); QTextBlockFormat paragraphFormat = blockFormat; paragraphFormat.setAlignment(Qt::AlignJustify); paragraphFormat.setTextIndent(32); cursor.setBlockFormat(paragraphFormat); cursor.insertText(tr("Text can be formatted so that the first " "line in a paragraph has its own margin. " "This makes the text more readable.")); cursor.insertBlock(); QTextBlockFormat reverseFormat = blockFormat; reverseFormat.setAlignment(Qt::AlignJustify); reverseFormat.setTextIndent(32); cursor.setBlockFormat(reverseFormat); cursor.insertText(tr("The direction of the text can be reversed. " "This is useful for right-to-left " "languages.")); editor->setWindowTitle(tr("Text Block Formats")); editor->resize(480, 480); editor->show(); return app.exec(); }
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; }
ScriptFormatter::ScriptFormatter( QQmlEngine* newEngine, QObject *parent ) : QObject(parent) { QFont baseFont; //The base from which all other fonts are derived baseFont.setBold( false ); baseFont.setCapitalization( QFont::MixedCase ); baseFont.setFamily( "Courier" ); baseFont.setItalic( false ); baseFont.setPointSize( 12 ); baseFont.setStyleHint( QFont::Courier ); QTextBlockFormat baseFormat; baseFormat.setAlignment( Qt::AlignLeft ); baseFormat.setIndent( 0 ); baseFormat.setLineHeight( 1, QTextBlockFormat::SingleHeight ); //The first argument should be ignored according to the documentation, since we're setting the LineHeightType (2nd argument) to single height baseFormat.setNonBreakableLines( false ); //baseFormat.setPageBreakPolicy( QTextFormat::PageBreak_Auto ); baseFormat.setTextIndent( 0 ); baseFormat.setTopMargin( 0 ); baseFormat.setBottomMargin( 0 ); baseFormat.setLeftMargin( 0 ); baseFormat.setRightMargin( 0 ); baseFormat.setNonBreakableLines( false ); //Scenes are left-aligned, bold, and all caps sceneFont = QFont( baseFont ); sceneFont.setBold( true ); sceneFont.setCapitalization( QFont::AllUppercase ); sceneBlockFormat = QTextBlockFormat( baseFormat ); sceneBlockFormat.setAlignment( Qt::AlignLeft ); //sceneBlockFormat.setPageBreakPolicy( QTextFormat::PageBreak_AlwaysBefore ); //Actions are left-aligned actionFont = QFont( baseFont ); actionBlockFormat = QTextBlockFormat( baseFormat ); actionBlockFormat.setAlignment( Qt::AlignLeft ); //Character names are centered and all caps characterFont = QFont( baseFont ); characterFont.setCapitalization( QFont::AllUppercase ); characterBlockFormat = QTextBlockFormat( baseFormat ); characterBlockFormat.setAlignment( Qt::AlignHCenter ); //characterBlockFormat.setPageBreakPolicy( QTextFormat::PageBreak_AlwaysBefore ); //Dialog is centered dialogFont = QFont( baseFont ); dialogBlockFormat = QTextBlockFormat( baseFormat ); dialogBlockFormat.setAlignment( Qt::AlignHCenter ); //dialogBlockFormat.setPageBreakPolicy( QTextFormat::PageBreak_AlwaysAfter ); //Parentheticals are centered and italicized parentheticalFont = QFont( baseFont ); parentheticalFont.setItalic( true ); parentheticalBlockFormat = QTextBlockFormat( baseFormat ); parentheticalBlockFormat.setAlignment( Qt::AlignHCenter ); //Transitions are right-aligned and all caps transitionFont = QFont( baseFont ); transitionFont.setCapitalization( QFont::AllUppercase ); transitionBlockFormat = QTextBlockFormat( baseFormat ); transitionBlockFormat.setAlignment( Qt::AlignRight ); //Shots are left-aligned and all caps shotFont = QFont( baseFont ); shotFont.setCapitalization( QFont::AllUppercase ); shotBlockFormat = QTextBlockFormat( baseFormat ); shotBlockFormat.setAlignment( Qt::AlignLeft ); //Act breaks are centered, bold, and underlined actBreakFont = QFont( baseFont ); actBreakFont.setBold( true ); actBreakFont.setUnderline( true ); actBreakBlockFormat = QTextBlockFormat( baseFormat ); actBreakBlockFormat.setAlignment( Qt::AlignHCenter ); }
void WChatLog::ChatLog_EventsDisplay(const CArrayPtrEvents & arraypEvents, int iEventStart) { Assert(iEventStart >= 0); Assert(m_oTextBlockComposing.isValid()); // CSocketXmpp * pSocket = m_pContactOrGroup->Xmpp_PGetSocketOnlyIfReady(); OCursorSelectBlock oCursor(m_oTextBlockComposing); QTextBlock oTextBlockEvent; // Text block for each event to insert IEvent ** ppEventStop; IEvent ** ppEventFirst = arraypEvents.PrgpGetEventsStop(OUT &ppEventStop) + iEventStart; IEvent ** ppEvent = ppEventFirst; if (!m_fDisplayAllMessages) { // For performance, limit the display to the last 100 events if (ppEventStop != NULL) { IEvent ** ppEventStart = ppEventStop - 100; if (ppEventStart > ppEvent) { ppEvent = ppEventStart; QTextBlockFormat oFormat; oFormat.setAlignment(Qt::AlignHCenter); oFormat.setBackground(c_brushSilver); // Use a silver color oCursor.setBlockFormat(oFormat); g_strScratchBufferStatusBar.Format("<a href='" d_SzMakeCambrianAction(d_szCambrianAction_DisplayAllHistory) "'>Display complete history ($I messages)</a>", arraypEvents.GetSize()); oCursor.insertHtml(g_strScratchBufferStatusBar); oCursor.AppendBlockBlank(); } } } while (ppEvent < ppEventStop) { IEvent * pEvent = *ppEvent++; AssertValidEvent(pEvent); if (pEvent->m_tsEventID >= m_tsMidnightNext) { QDateTime dtl = QDateTime::fromMSecsSinceEpoch(pEvent->m_tsEventID).toLocalTime(); QDate date = dtl.date(); // Strip the time of the day m_tsMidnightNext = QDateTime(date).toMSecsSinceEpoch() + d_ts_cDays; // I am sure there is a more elegant way to strip the time from a date, however at the moment I don't have time to investigate a better solution (and this code works) QTextBlockFormat oFormatBlock; oFormatBlock.setAlignment(Qt::AlignHCenter); oFormatBlock.setBackground(c_brushSilver); oCursor.setBlockFormat(oFormatBlock); QTextCharFormat oFormatChar; // = oCursor.charFormat(); oFormatChar.setFontWeight(QFont::Bold); //oFormatChar.setFontItalic(true); //oCursor.setCharFormat(oFormatChar); oCursor.insertText(date.toString("dddd MMMM d, yyyy"), oFormatChar); oCursor.AppendBlockBlank(); } oTextBlockEvent = oCursor.block(); // Get the current block under the cursor Endorse(oTextBlockEvent.userData() == NULL); if (pEvent->m_uFlagsEvent & IEvent::FE_kfReplacing) { MessageLog_AppendTextFormatSev(eSeverityComment, "Attempting to replace Event ID $t\n", pEvent->m_tsEventID); QTextBlock oTextBlockUpdate; QTextBlock oTextBlockTemp = document()->lastBlock(); IEvent * pEventOld = pEvent; const EEventClass eEventClassUpdater = pEvent->Event_FIsEventTypeSent() ? CEventUpdaterSent::c_eEventClass : CEventUpdaterReceived::c_eEventClass; // Which updater to search for // The event is replacing an older event. This code is a bit complex because the Chat Log may not display all events and therefore we need to find the most recent block displaying the most recent event. IEvent ** ppEventStop; IEvent ** ppEventFirst = pEvent->m_pVaultParent_NZ->m_arraypaEvents.PrgpGetEventsStop(OUT &ppEventStop); IEvent ** ppEventCompare = ppEventStop; // Search the array from the end, as the event to search is likely to be a recent one while (ppEventFirst < ppEventCompare) { // Find the updater which should be right before the replacing event IEvent * pEventTemp = *--ppEventCompare; TryAgain: if (pEventTemp == pEventOld && ppEventFirst < ppEventCompare) { CEventUpdaterSent * pEventUpdater = (CEventUpdaterSent *)*--ppEventCompare; // Get the updater which is just before the event if (pEventUpdater->EGetEventClass() != eEventClassUpdater) { MessageLog_AppendTextFormatSev(eSeverityErrorWarning, "\t Missing Updater for Event ID $t ({tL}); instead found class '$U' with Event ID $t.\n", pEventTemp->m_tsEventID, pEventTemp->m_tsEventID, pEventUpdater->EGetEventClass(), pEventUpdater->m_tsEventID); pEvent->m_uFlagsEvent &= ~IEvent::FE_kfReplacing; // Remove the bit to avoid displaying the error again and again pEvent->m_pVaultParent_NZ->SetModified(); // Save the change continue; } const TIMESTAMP tsEventIdOld = pEventUpdater->m_tsEventIdOld; MessageLog_AppendTextFormatSev(eSeverityNoise, "\t [$i] Found updater: $t -> $t\n", ppEventCompare - ppEventFirst, pEventUpdater->m_tsEventIdNew, tsEventIdOld); // Now, search for the block containing the replacement event while (oTextBlockTemp.isValid()) { OTextBlockUserDataEvent * pUserData = (OTextBlockUserDataEvent *)oTextBlockTemp.userData(); if (pUserData != NULL) { TIMESTAMP_DELTA dtsEvent = (pUserData->m_pEvent->m_tsEventID - tsEventIdOld); MessageLog_AppendTextFormatCo(d_coPurple, "Comparing block Event ID $t with $t: dtsEvent = $T\n", pUserData->m_pEvent->m_tsEventID, tsEventIdOld, dtsEvent); if (dtsEvent <= 0) { if (dtsEvent == 0) { MessageLog_AppendTextFormatSev(eSeverityNoise, "\t Found matching textblock for replacement: Event ID $t -> $t\n", pEventOld->m_tsEventID, tsEventIdOld); oTextBlockUpdate = oTextBlockTemp; } break; } } oTextBlockTemp = oTextBlockTemp.previous(); } // while // Keep searching in case there are chained updated events while (ppEventFirst < ppEventCompare) { pEventTemp = *--ppEventCompare; if (pEventTemp->m_tsEventID == tsEventIdOld) { MessageLog_AppendTextFormatSev(eSeverityNoise, "\t [$i] Found chained replacement: Event ID $t -> $t\n", ppEventCompare - ppEventFirst, pEvent->m_tsEventID, tsEventIdOld); pEventTemp->m_uFlagsEvent |= IEvent::FE_kfReplaced; pEventOld = pEventTemp; goto TryAgain; } } // while } // if } // while if (oTextBlockUpdate.isValid()) { MessageLog_AppendTextFormatSev(eSeverityNoise, "\t Event ID $t is updating its old Event ID $t\n", pEvent->m_tsEventID, pEventOld->m_tsEventID); OCursorSelectBlock oCursorEventOld(oTextBlockUpdate); pEvent->ChatLogUpdateTextBlock(INOUT &oCursorEventOld); continue; } MessageLog_AppendTextFormatSev(eSeverityErrorWarning, "Event ID $t is replacing another event which cannot be found\n", pEvent->m_tsEventID); } // if (replacing) oTextBlockEvent.setUserData(PA_CHILD new OTextBlockUserDataEvent(pEvent)); // Assign an event for each text block pEvent->ChatLogUpdateTextBlock(INOUT &oCursor); if ((pEvent->m_uFlagsEvent & IEvent::FE_kfEventHidden) == 0) oCursor.AppendBlockBlank(); // If the event is visible, then add a new text block (otherwise it will reuse the same old block) else oTextBlockEvent.setUserData(NULL); // Since we are reusing the same block, delete its userdata so we may assing another OTextBlockUserDataEvent } // while m_oTextBlockComposing = oCursor.block(); ChatLog_ChatStateTextAppend(INOUT oCursor); Widget_ScrollToEnd(INOUT this); } // ChatLog_EventsDisplay()
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); }
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++; }
QTextDocument * Exporter::buildFinalDoc() { //search for checked items : QDomDocument domDoc = hub->project()->mainTreeDomDoc(); QDomElement root = domDoc.documentElement(); QList<QDomElement> itemList = searchForCheckedItems(root); if(itemList.size() == 0) return new QTextDocument(); // set up the progress bar : QWidget *progressWidget = new QWidget(this, Qt::Dialog | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint); QHBoxLayout *progressLayout = new QHBoxLayout(progressWidget); QProgressBar *progressBar = new QProgressBar(progressWidget); int progressValue = 0; progressLayout->addWidget(progressBar); progressWidget->setLayout(progressLayout); progressBar->setMaximum(itemList.size()); progressBar->setValue(progressValue); progressWidget->show(); // QString debug; // qDebug() << "itemList" << debug.setNum(itemList->size()); QTextDocument *textDocument = new QTextDocument(this); QTextEdit *edit = new QTextEdit(this); textDocument->setDefaultStyleSheet("p, li { white-space: pre-wrap; } p{line-height: 2em; font-family:'Liberation Serif'; font-size:12pt;margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:72px;}"); for(int i = 0; i < itemList.size(); ++i){ QDomElement element = itemList.at(i); QTextCursor *tCursor = new QTextCursor(textDocument); QTextBlockFormat blockFormatLeft; blockFormatLeft.setBottomMargin(0); blockFormatLeft.setTopMargin(0); blockFormatLeft.setTextIndent(72); blockFormatLeft.setLineHeight(200, QTextBlockFormat::ProportionalHeight); blockFormatLeft.setAlignment(Qt::AlignJustify); QTextCharFormat charFormatLeft; charFormatLeft.setFontPointSize(12); charFormatLeft.setFontFamily("Courrier"); QTextBlockFormat blockFormatCenter; blockFormatCenter.setAlignment(Qt::AlignCenter); if(element.tagName() != "separator"){ qDebug() << "element name : "+ element.attribute("name"); MainTextDocument *textDoc = hub->project()->findChild<MainTextDocument *>("textDoc_" + element.attribute("number")); MainTextDocument *synDoc = hub->project()->findChild<MainTextDocument *>("synDoc_" + element.attribute("number")); MainTextDocument *noteDoc = hub->project()->findChild<MainTextDocument *>("noteDoc_" + element.attribute("number")); QTextDocumentFragment textFrag(prepareTextDoc(textDoc)); QTextDocumentFragment synFrag(prepareSynDoc(synDoc)); QTextDocumentFragment noteFrag(prepareNoteDoc(noteDoc)); edit->setDocument(textDocument); if(element.tagName() == "book"){ textDocument->setMetaInformation(QTextDocument::DocumentTitle,element.attribute("name", "")); edit->append("<h1>" + element.attribute("name", "") + "</h1>"); tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1); tCursor->mergeBlockFormat(blockFormatCenter); edit->append("<h4>" + QDateTime::currentDateTime().toString() + "</h4>"); tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1); tCursor->mergeBlockFormat(blockFormatCenter); edit->append("<br>"); edit->append("<br>"); } if(element.tagName() == "act"){ edit->append("<br>"); edit->append("<br>"); edit->append("<h2>" + element.attribute("name", "") + "</h2>"); tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1); tCursor->mergeBlockFormat(blockFormatCenter); edit->append("<br>"); } if(element.tagName() == "chapter"){ edit->append("<br>"); edit->append("<br>"); edit->append("<h2>" + element.attribute("name", "") + "</h2>"); tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1); tCursor->mergeBlockFormat(blockFormatCenter); edit->append("<br>"); } if(element.tagName() == "scene" && ui->setSceneTitlesComboBox->currentIndex() != 0){ QString sceneTitle; switch (ui->setSceneTitlesComboBox->currentIndex()){ case 1: sceneTitle = element.attribute("name", ""); break; case 2: sceneTitle = "###"; break; case 3: sceneTitle = "***"; break; default: sceneTitle = element.attribute("name", ""); break; } edit->append("<br>"); edit->append("<h3>" + sceneTitle + "</h3>"); tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1); tCursor->mergeBlockFormat(blockFormatCenter); edit->append("<br>"); } if(ui->synopsisCheckBox->isChecked() && !synFrag.isEmpty()){ edit->append("<br>"); edit->append("<h4>" + tr("Synopsis") + "</h4>"); tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1); tCursor->mergeBlockFormat(blockFormatCenter); edit->append("<br>"); tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1); tCursor->insertBlock(blockFormatLeft, charFormatLeft); tCursor->insertFragment(synFrag); } if(ui->notesCheckBox->isChecked() && !noteFrag.isEmpty()){ edit->append("<br>"); edit->append("<h4>" + tr("Note") + "</h4>"); tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1); tCursor->mergeBlockFormat(blockFormatCenter); edit->append("<br>"); tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1); tCursor->insertBlock(blockFormatLeft, charFormatLeft); tCursor->insertFragment(noteFrag); } if(ui->storyCheckBox->isChecked()){ if((ui->synopsisCheckBox->isChecked() || ui->notesCheckBox->isChecked()) && !textFrag.isEmpty()){ tCursor->insertBlock(); tCursor->insertHtml("<h4>" + tr("Story") + "</h4>"); tCursor->mergeBlockFormat(blockFormatCenter); tCursor->insertBlock(); } tCursor->insertHtml("<br>"); // tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1); tCursor->insertBlock(blockFormatLeft, charFormatLeft); tCursor->insertFragment(textFrag); // edit->append(textFrag->toHtml()); } } else if(element.tagName() == "separator"){ edit->append("<br>"); edit->append("<h3>#</h3>"); tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1); tCursor->mergeBlockFormat(blockFormatCenter); edit->append("<br>"); tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1); tCursor->mergeBlockFormat(blockFormatLeft); } progressValue += 1; progressBar->setValue(progressValue); } QRegExp reg("-qt-paragraph-type:.*;|margin-top:.*;|margin-bottom:.*;|margin-left:.*;|margin-right:.*;|-qt-block-indent:.*;|text-indent:.*;|font-family:.*;|font-size:.*;"); reg.setMinimal(true); textDocument->setHtml(textDocument->toHtml().remove(reg)); //find and change final page css style : //textDocument->setDefaultStyleSheet("p, li { white-space: pre-wrap; } p{line-height: 2em; font-family:'Liberation Serif'; font-size:14pt;margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:72px;}"); // <style type="text/css"> // p, li { white-space: pre-wrap; } // </style> // tCursor // qDebug() << textDocument->toHtml(); progressWidget->close(); return textDocument; }
TableauDeRemplissage::TableauDeRemplissage(int idEvenement, QObject *parent) : Etat(tr("Tableau de remplissage"), idEvenement, parent) { QSqlQuery query; if (query.prepare("select *" " from tableau_de_remplissage" " where id_evenement=:id_evenement")) { query.bindValue(":id_evenement", idEvenement); if (query.exec()) { // FIXME : ce rapport devrait être une feuille de calcul QString symboleAcceptee = "●"; QString symboleProposee = "◍"; QString symbolePossible = "○"; QString symboleManquante = "◌"; QTextCursor c(this); QTextBlockFormat formatDuTitreDeLaLegende; formatDuTitreDeLaLegende.setBottomMargin(10); QTextCharFormat formatDesCaracteresDuTitreDeLaLegende; formatDesCaracteresDuTitreDeLaLegende.setUnderlineStyle(QTextCharFormat::SingleUnderline); QTextBlockFormat formatDesBlocsDeLaLegende; QTextCharFormat formatDesCaracteresDeLaLegende; QTextListFormat formatDeLaListeDeLaLegende; QTextBlockFormat formatDuBlocJour; formatDuBlocJour.setPageBreakPolicy(QTextFormat::PageBreak_AlwaysBefore); formatDuBlocJour.setAlignment(Qt::AlignCenter); formatDuBlocJour.setBottomMargin(20); QTextCharFormat formatDesCaracteresDuJour; formatDesCaracteresDuJour.setFontCapitalization(QFont::Capitalize); formatDesCaracteresDuJour.setFontPointSize(14); formatDesCaracteresDuJour.setFontWeight(QFont::Bold); QTextBlockFormat formatDuBlocTour; formatDuBlocTour.setTopMargin(20); QTextCharFormat formatDesCaracteresDuTour; formatDesCaracteresDuTour.setFontWeight(QFont::Bold); QTextBlockFormat formatDuBlocDesResponsables; QTextCharFormat formatDesCaracteresDesResponsables; QTextBlockFormat formatDuBlocDuRemplissage; QTextCharFormat formatDesCaracteresDuRemplissage; if (query.first()) { c.movePosition(QTextCursor::End); c.insertBlock(formatDuTitreDeLaLegende, formatDesCaracteresDuTitreDeLaLegende); c.insertText(tr("Légende")); c.insertBlock(formatDesBlocsDeLaLegende, formatDesCaracteresDeLaLegende); c.insertList(formatDeLaListeDeLaLegende); c.insertText(tr("%1 affectation acceptée ou validée").arg(symboleAcceptee)); c.insertText("\n"); c.insertText(tr("%1 affectation proposée, en attente d'acceptation").arg(symboleProposee)); c.insertText("\n"); c.insertText(tr("%1 affectation possible, à proposer ou valider").arg(symbolePossible)); c.insertText("\n"); c.insertText(tr("%1 affectation manquante, reste à créer").arg(symboleManquante)); QSqlRecord r = query.record(); do { QDate jour = r.value("debut_tour").toDate(); c.insertBlock(formatDuBlocJour, formatDesCaracteresDuJour); c.insertText(QLocale().toString(jour)); do { int min = r.value("min").toInt(), max = r.value("max").toInt(), possibles = r.value("nombre_affectations_possibles").toInt(), proposees = r.value("nombre_affectations_proposees").toInt(), acceptees = r.value("nombre_affectations_validees_ou_acceptees").toInt(), trouvees = acceptees + proposees + possibles, manquantes = trouvees < min ? min - trouvees : 0, enTrop = max < trouvees ? trouvees - max : 0; QString responsables = r.value("liste_responsables").toString(); c.insertBlock(formatDuBlocTour, formatDesCaracteresDuTour); c.insertText(tr("De %1 à %2 / %3") .arg(r.value("debut_tour").toTime().toString("H:mm")) .arg(r.value("fin_tour").toTime().toString("H:mm")) .arg(r.value("nom_poste").toString()) ); if (!responsables.isEmpty()) { c.insertBlock(formatDuBlocDesResponsables, formatDesCaracteresDesResponsables); c.insertText(tr("Responsable(s) : %1").arg(responsables)); } c.insertBlock(formatDuBlocDuRemplissage, formatDesCaracteresDuRemplissage); c.insertText(symboleAcceptee.repeated(acceptees)); c.insertText(symboleProposee.repeated(proposees)); c.insertText(symbolePossible.repeated(possibles)); c.insertText(symboleManquante.repeated(manquantes)); if (enTrop) c.insertText(tr(" (%n affectation(s) en trop)", "", enTrop)); query.next(); r = query.record(); } while (query.isValid() && r.value("debut_tour").toDate() == jour); } while (query.isValid()); } else { qWarning() << tr("Aucune affectation trouvée"); } } else { qCritical() << query.lastError(); } } else { qCritical() << query.lastError(); } }
void DetailsTable::createAsteroidCometTable(SkyObject *obj) { clearContents(); QTextCursor cursor = m_Document->rootFrame()->firstCursorPosition(); QString perihelionVal, orbitIdVal, neoVal, diamVal, rotPeriodVal, moidVal; QString orbitClassVal, albedoVal, dimVal, periodVal; // Add specifics data switch(obj->type()) { case SkyObject::ASTEROID: { KSAsteroid* ast = (KSAsteroid *)obj; // Perihelion perihelionVal = QString::number(ast->getPerihelion()) + " AU"; // Earth MOID moidVal = ast->getEarthMOID() == 0 ? QString("--") : QString::number(ast->getEarthMOID()) + QString(" AU"); // Orbit ID orbitIdVal = ast->getOrbitID(); // Orbit Class orbitClassVal = ast->getOrbitClass(); // NEO neoVal = ast->isNEO() ? i18n("Yes") : i18n("No"); // Albedo albedoVal = ast->getAlbedo() == 0 ? QString("--") : QString::number(ast->getAlbedo()); // Diameter diamVal = ast->getDiameter() == 0 ? QString("--") : QString::number(ast->getDiameter()) + QString(" km"); // Dimensions dimVal = ast->getDimensions().isEmpty() ? QString("--") : ast->getDimensions() + QString(" km"); // Rotation period rotPeriodVal = ast->getRotationPeriod() == 0 ? QString("--") : QString::number(ast->getRotationPeriod()) + QString(" h"); // Period periodVal = ast->getPeriod() == 0 ? QString("--") : QString::number(ast->getPeriod()) + QString(" y"); break; } case SkyObject::COMET: { KSComet* com = (KSComet *)obj; // Perihelion perihelionVal = QString::number(com->getPerihelion()) + " AU"; // Earth MOID moidVal = com->getEarthMOID() == 0 ? QString("--") : QString::number(com->getEarthMOID()) + QString(" AU"); // Orbit ID orbitIdVal = com->getOrbitID(); // Orbit Class orbitClassVal = com->getOrbitClass(); // NEO neoVal = com->isNEO() ? i18n("Yes") : i18n("No"); // Albedo albedoVal = com->getAlbedo() == 0 ? QString("--") : QString::number(com->getAlbedo()); // Diameter diamVal = com->getDiameter() == 0 ? QString("--") : QString::number(com->getDiameter()) + QString(" km"); // Dimensions dimVal = com->getDimensions().isEmpty() ? QString("--") : com->getDimensions() + QString(" km"); // Rotation period rotPeriodVal = com->getRotationPeriod() == 0 ? QString("--") : QString::number(com->getRotationPeriod()) + QString(" h"); // Period periodVal = com->getPeriod() == 0 ? QString("--") : QString::number(com->getPeriod()) + QString(" y"); break; } default: { return; } } // Set column width constraints QVector<QTextLength> constraints; constraints << QTextLength(QTextLength::PercentageLength, 25) << QTextLength(QTextLength::PercentageLength, 25) << QTextLength(QTextLength::PercentageLength, 25) << QTextLength(QTextLength::PercentageLength, 25); m_TableFormat.setColumnWidthConstraints(constraints); QTextTable *table = cursor.insertTable(6, 4, m_TableFormat); table->mergeCells(0, 0, 1, 4); QTextBlockFormat centered; centered.setAlignment(Qt::AlignCenter); table->cellAt(0, 0).firstCursorPosition().setBlockFormat(centered); table->cellAt(0, 0).firstCursorPosition().insertText(i18n("Asteroid/Comet details"), m_TableTitleCharFormat); table->cellAt(1, 0).firstCursorPosition().insertText(i18n("Perihelion:"), m_ItemNameCharFormat); table->cellAt(1, 0).firstCursorPosition().setBlockFormat(centered); table->cellAt(1, 1).firstCursorPosition().insertText(perihelionVal, m_ItemValueCharFormat); table->cellAt(2, 0).firstCursorPosition().insertText(i18n("Orbit ID:"), m_ItemNameCharFormat); table->cellAt(2, 0).firstCursorPosition().setBlockFormat(centered); table->cellAt(2, 1).firstCursorPosition().insertText(orbitIdVal, m_ItemValueCharFormat); table->cellAt(3, 0).firstCursorPosition().insertText(i18n("NEO:"), m_ItemNameCharFormat); table->cellAt(3, 0).firstCursorPosition().setBlockFormat(centered); table->cellAt(3, 1).firstCursorPosition().insertText(neoVal, m_ItemValueCharFormat); table->cellAt(4, 0).firstCursorPosition().insertText(i18n("Diameter:"), m_ItemNameCharFormat); table->cellAt(4, 0).firstCursorPosition().setBlockFormat(centered); table->cellAt(4, 1).firstCursorPosition().insertText(diamVal, m_ItemValueCharFormat); table->cellAt(5, 0).firstCursorPosition().insertText(i18n("Rotation period:"), m_ItemNameCharFormat); table->cellAt(5, 0).firstCursorPosition().setBlockFormat(centered); table->cellAt(5, 1).firstCursorPosition().insertText(rotPeriodVal, m_ItemValueCharFormat); table->cellAt(1, 2).firstCursorPosition().insertText(i18n("Earth MOID:"), m_ItemNameCharFormat); table->cellAt(1, 2).firstCursorPosition().setBlockFormat(centered); table->cellAt(1, 3).firstCursorPosition().insertText(moidVal, m_ItemValueCharFormat); table->cellAt(2, 2).firstCursorPosition().insertText(i18n("Orbit class:"), m_ItemNameCharFormat); table->cellAt(2, 2).firstCursorPosition().setBlockFormat(centered); table->cellAt(2, 3).firstCursorPosition().insertText(orbitClassVal, m_ItemValueCharFormat); table->cellAt(3, 2).firstCursorPosition().insertText(i18n("Albedo:"), m_ItemNameCharFormat); table->cellAt(3, 2).firstCursorPosition().setBlockFormat(centered); table->cellAt(3, 3).firstCursorPosition().insertText(albedoVal, m_ItemValueCharFormat); table->cellAt(4, 2).firstCursorPosition().insertText(i18n("Dimensions:"), m_ItemNameCharFormat); table->cellAt(4, 2).firstCursorPosition().setBlockFormat(centered); table->cellAt(4, 3).firstCursorPosition().insertText(dimVal, m_ItemValueCharFormat); table->cellAt(5, 2).firstCursorPosition().insertText(i18n("Period:"), m_ItemNameCharFormat); table->cellAt(5, 2).firstCursorPosition().setBlockFormat(centered); table->cellAt(5, 3).firstCursorPosition().insertText(periodVal, m_ItemValueCharFormat); }
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(); }