Ejemplo n.º 1
0
void QTextOdfWriter::writeCharacterFormat(QXmlStreamWriter &writer, QTextCharFormat format, int formatIndex) const
{
    writer.writeStartElement(styleNS, QString::fromLatin1("style"));
    writer.writeAttribute(styleNS, QString::fromLatin1("name"), QString::fromLatin1("c%1").arg(formatIndex));
    writer.writeAttribute(styleNS, QString::fromLatin1("family"), QString::fromLatin1("text"));
    writer.writeEmptyElement(styleNS, QString::fromLatin1("text-properties"));
    if (format.fontItalic())
        writer.writeAttribute(foNS, QString::fromLatin1("font-style"), QString::fromLatin1("italic"));
    if (format.hasProperty(QTextFormat::FontWeight) && format.fontWeight() != QFont::Normal) {
        QString value;
        if (format.fontWeight() == QFont::Bold)
            value = QString::fromLatin1("bold");
        else
            value = QString::number(format.fontWeight() * 10);
        writer.writeAttribute(foNS, QString::fromLatin1("font-weight"), value);
    }
    if (format.hasProperty(QTextFormat::FontFamily))
        writer.writeAttribute(foNS, QString::fromLatin1("font-family"), format.fontFamily());
    else
        writer.writeAttribute(foNS, QString::fromLatin1("font-family"), QString::fromLatin1("Sans")); // Qt default
    if (format.hasProperty(QTextFormat::FontPointSize))
        writer.writeAttribute(foNS, QString::fromLatin1("font-size"), QString::fromLatin1("%1pt").arg(format.fontPointSize()));
    if (format.hasProperty(QTextFormat::FontCapitalization)) {
        switch(format.fontCapitalization()) {
        case QFont::MixedCase:
            writer.writeAttribute(foNS, QString::fromLatin1("text-transform"), QString::fromLatin1("none")); break;
        case QFont::AllUppercase:
            writer.writeAttribute(foNS, QString::fromLatin1("text-transform"), QString::fromLatin1("uppercase")); break;
        case QFont::AllLowercase:
            writer.writeAttribute(foNS, QString::fromLatin1("text-transform"), QString::fromLatin1("lowercase")); break;
        case QFont::Capitalize:
            writer.writeAttribute(foNS, QString::fromLatin1("text-transform"), QString::fromLatin1("capitalize")); break;
        case QFont::SmallCaps:
            writer.writeAttribute(foNS, QString::fromLatin1("font-variant"), QString::fromLatin1("small-caps")); break;
        }
    }
    if (format.hasProperty(QTextFormat::FontLetterSpacing))
        writer.writeAttribute(foNS, QString::fromLatin1("letter-spacing"), pixelToPoint(format.fontLetterSpacing()));
    if (format.hasProperty(QTextFormat::FontWordSpacing) && format.fontWordSpacing() != 0)
            writer.writeAttribute(foNS, QString::fromLatin1("word-spacing"), pixelToPoint(format.fontWordSpacing()));
    if (format.hasProperty(QTextFormat::FontUnderline))
        writer.writeAttribute(styleNS, QString::fromLatin1("text-underline-type"),
                format.fontUnderline() ? QString::fromLatin1("single") : QString::fromLatin1("none"));
    if (format.hasProperty(QTextFormat::FontOverline)) {
        //   bool   fontOverline () const  TODO
    }
    if (format.hasProperty(QTextFormat::FontStrikeOut))
        writer.writeAttribute(styleNS,QString::fromLatin1( "text-line-through-type"),
                format.fontStrikeOut() ? QString::fromLatin1("single") : QString::fromLatin1("none"));
    if (format.hasProperty(QTextFormat::TextUnderlineColor))
        writer.writeAttribute(styleNS, QString::fromLatin1("text-underline-color"), format.underlineColor().name());
    if (format.hasProperty(QTextFormat::FontFixedPitch)) {
        //   bool   fontFixedPitch () const  TODO
    }
    if (format.hasProperty(QTextFormat::TextUnderlineStyle)) {
        QString value;
        switch (format.underlineStyle()) {
        case QTextCharFormat::NoUnderline: value = QString::fromLatin1("none"); break;
        case QTextCharFormat::SingleUnderline: value = QString::fromLatin1("solid"); break;
        case QTextCharFormat::DashUnderline: value = QString::fromLatin1("dash"); break;
        case QTextCharFormat::DotLine: value = QString::fromLatin1("dotted"); break;
        case QTextCharFormat::DashDotLine: value = QString::fromLatin1("dash-dot"); break;
        case QTextCharFormat::DashDotDotLine: value = QString::fromLatin1("dot-dot-dash"); break;
        case QTextCharFormat::WaveUnderline: value = QString::fromLatin1("wave"); break;
        case QTextCharFormat::SpellCheckUnderline: value = QString::fromLatin1("none"); break;
        }
        writer.writeAttribute(styleNS, QString::fromLatin1("text-underline-style"), value);
    }
    if (format.hasProperty(QTextFormat::TextVerticalAlignment)) {
        QString value;
        switch (format.verticalAlignment()) {
        case QTextCharFormat::AlignMiddle:
        case QTextCharFormat::AlignBaseline:
        case QTextCharFormat::AlignNormal: value = QString::fromLatin1("0%"); break;
        case QTextCharFormat::AlignSuperScript: value = QString::fromLatin1("super"); break;
        case QTextCharFormat::AlignSubScript: value = QString::fromLatin1("sub"); break;
        case QTextCharFormat::AlignTop: value = QString::fromLatin1("100%"); break;
        case QTextCharFormat::AlignBottom : value = QString::fromLatin1("-100%"); break;
        }
        writer.writeAttribute(styleNS, QString::fromLatin1("text-position"), value);
    }
    if (format.hasProperty(QTextFormat::TextOutline))
        writer.writeAttribute(styleNS, QString::fromLatin1("text-outline"), QString::fromLatin1("true"));
    if (format.hasProperty(QTextFormat::TextToolTip)) {
        //   QString   toolTip () const  TODO
    }
    if (format.hasProperty(QTextFormat::IsAnchor)) {
        //   bool   isAnchor () const  TODO
    }
    if (format.hasProperty(QTextFormat::AnchorHref)) {
        //   QString   anchorHref () const  TODO
    }
    if (format.hasProperty(QTextFormat::AnchorName)) {
        //   QString   anchorName () const  TODO
    }
    if (format.hasProperty(QTextFormat::ForegroundBrush)) {
        QBrush brush = format.foreground();
        writer.writeAttribute(foNS, QString::fromLatin1("color"), brush.color().name());
    }
    if (format.hasProperty(QTextFormat::BackgroundBrush)) {
        QBrush brush = format.background();
        writer.writeAttribute(foNS, QString::fromLatin1("background-color"), brush.color().name());
    }

    writer.writeEndElement(); // style
}
Ejemplo n.º 2
0
void MailEditorMainWindow::onTextBoldTriggerred(bool checked)
  {
  QTextCharFormat fmt;
  fmt.setFontWeight(checked ? QFont::Bold : QFont::Normal);
  mergeFormatOnWordOrSelection(fmt);
  }
Ejemplo n.º 3
0
void MailEditorMainWindow::onTextFamilyChanged(const QString& f)
  {
  QTextCharFormat fmt;
  fmt.setFontFamily(f);
  mergeFormatOnWordOrSelection(fmt);
  }
Ejemplo n.º 4
0
void TextContent::drawContent(QPainter * painter, const QRect & targetRect, Qt::AspectRatioMode ratio)
{
    Q_UNUSED(ratio)

    // check whether we're drawing shaped
    const bool shapedPaint = hasShape() && !m_shapeRect.isEmpty();
    QPointF shapeOffset = m_shapeRect.topLeft();

    // scale painter for adapting the Text Rect to the Contents Rect
    QRect sourceRect = shapedPaint ? m_shapeRect : m_textRect;
    painter->save();
    painter->translate(targetRect.topLeft());
    if (sourceRect.width() > 0 && sourceRect.height() > 0) {
        qreal xScale = (qreal)targetRect.width() / (qreal)sourceRect.width();
        qreal yScale = (qreal)targetRect.height() / (qreal)sourceRect.height();
        if (!qFuzzyCompare(xScale, (qreal)1.0) || !qFuzzyCompare(yScale, (qreal)1.0))
            painter->scale(xScale, yScale);
    }

    // shape
    //const bool drawHovering = RenderOpts::HQRendering ? false : isSelected();
    if (shapedPaint)
        painter->translate(-shapeOffset);
    //if (shapedPaint && drawHovering)
    //    painter->strokePath(m_shapePath, QPen(Qt::red, 0));

    // TEMP - for PDF exporting - standard rich text document drawing
    if (RenderOpts::PDFExporting) {
        if (shapedPaint)
            QMessageBox::information(0, tr("PDF Export Warning"), tr("Shaped text could not be exported in PDF"), QMessageBox::Ok);
        QAbstractTextDocumentLayout::PaintContext pCtx;
        m_text->documentLayout()->draw(painter, pCtx);
    } else {
        // manual drawing
        QPointF blockPos = shapedPaint ? QPointF(0, 0) : -m_textRect.topLeft();

        // 1. for each Text Block
        int blockRectIdx = 0;
        for (QTextBlock tb = m_text->begin(); tb.isValid(); tb = tb.next()) {
            if (!tb.isVisible() || blockRectIdx > m_blockRects.size())
                continue;

            // 1.1. compute text insertion position
            const QRect & blockRect = m_blockRects[blockRectIdx++];
            QPointF iPos = shapedPaint ? blockPos : blockPos - blockRect.topLeft();
            blockPos += QPointF(0, blockRect.height());

            qreal curLen = 8;

            // 1.2. iterate over text fragments
            for (QTextBlock::iterator tbIt = tb.begin(); !(tbIt.atEnd()); ++tbIt) {
                QTextFragment frag = tbIt.fragment();
                if (!frag.isValid())
                    continue;

                // 1.2.1. setup painter and metrics for text fragment
                QTextCharFormat format = frag.charFormat();
                QFont font = format.font();
                painter->setFont(font);
                painter->setPen(format.foreground().color());
                painter->setBrush(Qt::NoBrush);
                QFontMetrics metrics(font);

                // 1.2.2. draw each character
                QString text = frag.text();
                foreach (const QChar & textChar, text) {
                    const qreal charWidth = metrics.width(textChar);
                    if (shapedPaint) {
                        // find point on shape and angle
                        qreal t = m_shapePath.percentAtLength(curLen);
                        QPointF pt = m_shapePath.pointAtPercent(t);
                        qreal angle = -m_shapePath.angleAtPercent(t);
                        if (m_shakeRadius > 0)
                            pt += QPointF(1 + (qrand() % m_shakeRadius) - m_shakeRadius/2, 1 + (qrand() % (2*m_shakeRadius)) - m_shakeRadius);

                        // draw rotated letter
                        painter->save();
                        painter->translate(pt);
                        painter->rotate(angle);
                        painter->drawText(iPos, textChar);
                        painter->restore();

                        curLen += charWidth;
                    } else {
                        painter->drawText(iPos, textChar);
                        iPos += QPointF(charWidth, 0);
                    }
                }
            }
        }
    }

    painter->restore();
}
Ejemplo n.º 5
0
void
FormText::setCfg( const Cfg::Text & c )
{
	setPlainText( QString() );

	QFont f = font();
	QTextCharFormat fmt = textCursor().charFormat();
	QTextBlockFormat b = textCursor().blockFormat();

	foreach( const Cfg::TextStyle & s, c.text() )
	{
		if( s.style().contains( Cfg::c_normalStyle ) )
		{
			f.setWeight( QFont::Normal );
			f.setItalic( false );
			f.setUnderline( false );

			fmt.setFontWeight( QFont::Normal );
			fmt.setFontItalic( false );
			fmt.setFontUnderline( false );
		}
		else
		{
			if( s.style().contains( Cfg::c_boldStyle ) )
			{
				f.setWeight( QFont::Bold );
				fmt.setFontWeight( QFont::Bold );
			}
			else
			{
				f.setWeight( QFont::Normal );
				fmt.setFontWeight( QFont::Normal );
			}

			if( s.style().contains( Cfg::c_italicStyle ) )
			{
				f.setItalic( true );
				fmt.setFontItalic( true );
			}
			else
			{
				f.setItalic( false );
				fmt.setFontItalic( false );
			}

			if( s.style().contains( Cfg::c_underlineStyle ) )
			{
				f.setUnderline( true );
				fmt.setFontUnderline( true );
			}
			else
			{
				f.setUnderline( false );
				fmt.setFontUnderline( false );
			}
		}

		Cfg::initBlockFormat( b, s );

		f.setPointSize( s.fontSize() );

		fmt.setFontPointSize( s.fontSize() );

		setFont( f );

		QTextCursor cursor = textCursor();
		cursor.movePosition( QTextCursor::End );
		cursor.setCharFormat( fmt );
		cursor.setBlockFormat( b );
		cursor.insertText( s.text() );
		setTextCursor( cursor );
	}

	document()->clearUndoRedoStacks();

	setObjectId( c.objectId() );

	setTextWidth( c.textWidth() );

	setPos( QPointF( c.pos().x(), c.pos().y() ) );

	setLink( c.link() );

	QRectF r = boundingRect();
	r.moveTo( pos() );

	d->m_proxy->setRect( r );
}
Ejemplo n.º 6
0
int RichTextRenderer::fitToSize(const QSize& size, int minimumFontSize, int maximumFontSize)
{
	int width = size.width();
	int height = size.height();
	
	const QString sizeKey = QString("%1:%2:%3:%4").arg(html()).arg(width).arg(height).arg(minimumFontSize);
	
	// for centering
	qreal boxHeight = -1;
		
	double ptSize = -1;
	if(static_autoTextSizeCache.contains(sizeKey))
	{
		ptSize = *(static_autoTextSizeCache[sizeKey]);
		
		//qDebug()<<"RichTextRenderer::fitToSize(): size search: CACHE HIT: loaded size:"<<ptSize;
		
		// We go thru the much-more-verbose method of creating
		// the document and setting the html, width, merge cursor,
		// etc, just so we can get the document height after
		// setting the font size inorder to use it to center the textbox.
		// If we didnt nead the height, we could just use autoText->setFontSize()
		
		QTextDocument doc;
		doc.setTextWidth(width);
		if (Qt::mightBeRichText(html()))
			doc.setHtml(html());
		else
			doc.setPlainText(html());

			
		QTextCursor cursor(&doc);
		cursor.select(QTextCursor::Document);
		
		QTextCharFormat format;
		format.setFontPointSize(ptSize);
		cursor.mergeCharFormat(format);
		
		boxHeight = doc.documentLayout()->documentSize().height();
		
		setHtml(doc.toHtml());
	}
	else
	{
		double ptSize = minimumFontSize > 0 ? minimumFontSize : findFontSize();
		double sizeInc = 1;	// how big of a jump to add to the ptSize each iteration
		int count = 0;		// current loop iteration
		int maxCount = 100; 	// max iterations of the search loop
		bool done = false;
		
		double lastGoodSize = ptSize;
		QString lastGoodHtml = html();
		
		QTextDocument doc;
		
		qreal heightTmp;
		
		doc.setTextWidth(width);
		if (Qt::mightBeRichText(html()))
			doc.setHtml(html());
		else
			doc.setPlainText(html());

			
		QTextCursor cursor(&doc);
		cursor.select(QTextCursor::Document);
		
		QTextCharFormat format;
			
		while(!done && count++ < maxCount)
		{
			format.setFontPointSize(ptSize);
			cursor.mergeCharFormat(format);
			
			heightTmp = doc.documentLayout()->documentSize().height();
			
			if(heightTmp < height &&
			      ptSize < maximumFontSize)
			{
				lastGoodSize = ptSize;
				//lastGoodHtml = html();
				boxHeight = heightTmp;

				sizeInc *= 1.1;
// 				qDebug()<<"size search: "<<ptSize<<"pt was good, trying higher, inc:"<<sizeInc<<"pt";
				ptSize += sizeInc;

			}
			else
			{
// 				qDebug()<<"fitToSize: size search: last good ptsize:"<<lastGoodSize<<", stopping search";
				done = true;
			}
		}
		
		if(boxHeight < 0 && minimumFontSize <= 0) // didnt find a size
		{
			ptSize = 100;
			
			count = 0;
			done = false;
			sizeInc = 1;
			
			//qDebug()<<"RichTextRenderer::fitToSize(): size search: going UP failed, now I'll try to go DOWN";
			
			while(!done && count++ < maxCount)
			{
				
				format.setFontPointSize(ptSize);
				cursor.mergeCharFormat(format);
				
				heightTmp = doc.documentLayout()->documentSize().height();
				
				if(heightTmp < height)
				{
					lastGoodSize = ptSize;
					//lastGoodHtml = html();
					boxHeight = heightTmp;
	
					sizeInc *= 1.1;
					//qDebug()<<"size search: "<<ptSize<<"pt was good, trying higher, inc:"<<sizeInc<<"pt";
					ptSize -= sizeInc;
	
				}
				else
				{
					//qDebug()<<"SongSlideGroup::textToSlides(): size search: last good ptsize:"<<lastGoodSize<<", stopping search";
					done = true;
				}
			}
		}

		format.setFontPointSize(lastGoodSize);
		cursor.mergeCharFormat(format);
		
		setHtml(doc.toHtml());
		
		//qDebug()<<"RichTextRenderer::fitToSize(): size search: caching ptsize:"<<lastGoodSize<<", count: "<<count<<"( minimum size was:"<<minimumFontSize<<")";
		boxHeight = heightTmp;
		//static_autoTextSizeCache[sizeKey] = lastGoodSize;
		
		// We are using a QCache instead of a plain QMap, so that requires a pointer value 
		// Using QCache because the key for the cache could potentially become quite large if there are large amounts of HTML
		// and I dont want to just keep accumlating html in the cache infinitely
		static_autoTextSizeCache.insert(sizeKey, new double(lastGoodSize),1);
	}
	
	return (int)boxHeight;
	
}
void QMaliitPlatformInputContext::updatePreedit(const QDBusMessage &message)
{
    if (!inputMethodAccepted())
        return;

    QList<QVariant> arguments = message.arguments();
    if (arguments.count() != 5) {
        qWarning() << "QMaliitPlatformInputContext::updatePreedit: Received message from input method server with wrong parameters.";
        return;
    }

    d->preedit = arguments[0].toString();

    QList<QInputMethodEvent::Attribute> attributes;

    const QDBusArgument formats = arguments[1].value<QDBusArgument>();
    formats.beginArray();
    while (!formats.atEnd()) {
        formats.beginStructure();
        int start, length, preeditFace;
        formats >> start >> length >> preeditFace;
        formats.endStructure();

        QTextCharFormat format;

        enum PreeditFace {
            PreeditDefault,
            PreeditNoCandidates,
            PreeditKeyPress,      //!< Used for displaying the hwkbd key just pressed
            PreeditUnconvertible, //!< Inactive preedit region, not clickable
            PreeditActive,        //!< Preedit region with active suggestions

        };
        switch (PreeditFace(preeditFace)) {
        case PreeditDefault:
        case PreeditKeyPress:
            format.setUnderlineStyle(QTextCharFormat::SingleUnderline);
            format.setUnderlineColor(QColor(0, 0, 0));
            break;
        case PreeditNoCandidates:
            format.setUnderlineStyle(QTextCharFormat::SingleUnderline);
            format.setUnderlineColor(QColor(255, 0, 0));
            break;
        case PreeditUnconvertible:
            format.setForeground(QBrush(QColor(128, 128, 128)));
            break;
        case PreeditActive:
            format.setForeground(QBrush(QColor(153, 50, 204)));
            format.setFontWeight(QFont::Bold);
            break;
        default:
            break;
        }

        attributes << QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat, start, length, format);
    }
    formats.endArray();

    int replacementStart = arguments[2].toInt();
    int replacementLength = arguments[3].toInt();
    int cursorPos = arguments[4].toInt();

    if (debug)
        qWarning() << "updatePreedit" << d->preedit << replacementStart << replacementLength << cursorPos;

    if (cursorPos >= 0)
        attributes << QInputMethodEvent::Attribute(QInputMethodEvent::Cursor, cursorPos, 1, QVariant());

    QInputMethodEvent event(d->preedit, attributes);
    if (replacementStart || replacementLength)
        event.setCommitString(QString(), replacementStart, replacementLength);
    QCoreApplication::sendEvent(qGuiApp->focusObject(), &event);
}
Ejemplo n.º 8
0
void MainWindow::onTextCharFormatChanged( const QTextCharFormat & sFormat )
{
    QFont fnt = sFormat.font();
    m_pCmbFont->setCurrentText( fnt.family() );
    m_pCmbFontPointSize->setCurrentText(  QString::number( fnt.pointSize() ) );
}
Ejemplo n.º 9
0
QString FlatTextarea::getText(int32 start, int32 end) const {
	if (end >= 0 && end <= start) return QString();

	if (start < 0) start = 0;
	bool full = (start == 0) && (end < 0);

	QTextDocument *doc(document());
	QTextBlock from = full ? doc->begin() : doc->findBlock(start), till = (end < 0) ? doc->end() : doc->findBlock(end);
	if (till.isValid()) till = till.next();

	int32 possibleLen = 0;
	for (QTextBlock b = from; b != till; b = b.next()) {
		possibleLen += b.length();
	}
	QString result;
	result.reserve(possibleLen + 1);
	if (!full && end < 0) {
		end = possibleLen;
	}

	for (QTextBlock b = from; b != till; b = b.next()) {
		for (QTextBlock::Iterator iter = b.begin(); !iter.atEnd(); ++iter) {
			QTextFragment fragment(iter.fragment());
			if (!fragment.isValid()) continue;

			int32 p = full ? 0 : fragment.position(), e = full ? 0 : (p + fragment.length());
			if (!full) {
				if (p >= end || e <= start) {
					continue;
				}
			}

			QTextCharFormat f = fragment.charFormat();
			QString emojiText;
			QString t(fragment.text());
			if (!full) {
				if (p < start) {
					t = t.mid(start - p, end - start);
				} else if (e > end) {
					t = t.mid(0, end - p);
				}
			}
			QChar *ub = t.data(), *uc = ub, *ue = uc + t.size();
			for (; uc != ue; ++uc) {
				switch (uc->unicode()) {
				case 0xfdd0: // QTextBeginningOfFrame
				case 0xfdd1: // QTextEndOfFrame
				case QChar::ParagraphSeparator:
				case QChar::LineSeparator:
					*uc = QLatin1Char('\n');
					break;
				case QChar::Nbsp:
					*uc = QLatin1Char(' ');
					break;
				case QChar::ObjectReplacementCharacter:
					if (emojiText.isEmpty() && f.isImageFormat()) {
						QString imageName = static_cast<QTextImageFormat*>(&f)->name();
						if (imageName.midRef(0, 8) == qsl("emoji://")) {
							uint32 index = imageName.mid(8).toUInt(0, 16);
							const EmojiData *emoji = getEmoji(index);
							if (emoji) {
								emojiText = textEmojiString(emoji);
							}
						}
					}
					if (uc > ub) result.append(ub, uc - ub);
					if (!emojiText.isEmpty()) result.append(emojiText);
					ub = uc + 1;
				break;
				}
			}
			if (uc > ub) result.append(ub, uc - ub);
		}
		result.append('\n');
	}
	result.chop(1);
	return result;
}
Ejemplo n.º 10
0
Tools::Tools(bool thisIsABackup, QWidget *parent) : QToolBar(parent) {

	// This variable holds whether the toolbar is used for a backup or not (add and edit buttons disabled for backups)
	this->thisIsABackup = thisIsABackup;

	this->setFloatable(false);
	this->setMovable(false);
	this->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
	this->setIconSize(QSize(20,20));

	addBooking = new QToolButton;
	addBooking->setIcon(QIcon(":/images/add.png"));
	addBooking->setText("Add &New");
	addBooking->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
	addBooking->setStyleSheet("font-size: 11pt; font-weight: bold");
	addBooking->setFixedHeight(40);
	addBooking->setStatusTip("Add a new booking");
	if(thisIsABackup) addBooking->setEnabled(false);

	editBooking = new QToolButton;
	editBooking->setIcon(QIcon(":/images/edit.png"));
	editBooking->setText("&Edit");
	editBooking->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
	editBooking->setStyleSheet("font-size: 11pt; font-weight: bold");
	editBooking->setFixedHeight(40);
	editBooking->setStatusTip("Edit Booking");
	if(thisIsABackup) editBooking->setEnabled(false);

	gotoToday_but = new QToolButton;
	gotoToday_but->setIcon(QIcon(":/images/calendar.png"));
	gotoToday_but->setText("Go to &Today");
	gotoToday_but->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
	gotoToday_but->setStyleSheet("font-size: 11pt; font-weight: bold");
	gotoToday_but->setFixedHeight(40);
	gotoToday_but->setStatusTip("Go to Today");

	currentDate = QDate::currentDate();
	gotoPrev = new QToolButton;
	gotoPrev->setIcon(QIcon(":/images/left.png"));
	gotoPrev->setStatusTip("Go to previous day");
	gotoPrev->setFixedSize(50,40);
	gotoPrev->setShortcut(QKeySequence("Alt+Left"));
	gotoNext = new QToolButton;
	gotoNext->setIcon(QIcon(":/images/right.png"));
	gotoNext->setStatusTip("Go to next day");
	gotoNext->setFixedSize(50,40);
	gotoNext->setShortcut(QKeySequence("Alt+Right"));
	curDate = new QToolButton;
	curDate->setStatusTip("Select date from calendar");
	curDate->setText(QDate::currentDate().toString("dddd, dd MMM yyyy"));
	curDate->setStyleSheet("font-size: 11pt; font-weight: bold");
	curDate->setFixedSize(220,40);
	curDate->setPopupMode(QToolButton::InstantPopup);
	curDate->setShortcut(QKeySequence("Alt+C"));

	cal = new QCalendarWidget;
	cal->setMinimumDate(QDate(QDate::currentDate().year()-100,1,1));
	cal->setMaximumDate(QDate(QDate::currentDate().year()+100,12,31));
	cal->setFixedWidth(400);
	cal->setFixedHeight(300);
	cal->setGridVisible(true);
	cal->setStyleSheet("font-size: 12pt; font-weight: bold");
	QTextCharFormat format;
	format.setFontWeight(QFont::Bold);
	format.setBackground(QBrush(QColor(220,220,220)));
	cal->setHeaderTextFormat(format);
	m = new QMenu;
	QWidgetAction *a = new QWidgetAction(m);
	a->setDefaultWidget(cal);
	m->addAction(a);
	curDate->setMenu(m);
	m->installEventFilter(this);

	connect(m, SIGNAL(aboutToShow()), this, SLOT(clickForCalendar()));

	showCancelled = new QCheckBox("Also show cancelled bookings");

	filterAdv = new QToolButton;
	filterAdv->setCheckable(true);
	filterAdv->setText("&Search");
	filterAdv->setIcon(QIcon(":/images/search.png"));
	filterAdv->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
	filterAdv->setStyleSheet("font-size: 11pt; font-weight: bold");
	filterAdv->setFixedHeight(40);
	filter = new CustomLineEdit;
	filter->setStyleSheet("font-size: 11pt");

	this->addWidget(addBooking);
	this->addSeparator();
	this->addWidget(editBooking);
	this->addSeparator();
	this->addWidget(gotoToday_but);
	this->addWidget(gotoPrev);
	this->addWidget(curDate);
	this->addWidget(gotoNext);

	QWidget *separator1 = new QWidget;
	separator1->setSizePolicy(QSizePolicy::Expanding,
				 QSizePolicy::Expanding);
	QWidget *separator2 = new QWidget;
	separator2->setFixedWidth(10);
	QWidget *separator3 = new QWidget;
	separator3->setFixedWidth(10);

	this->addWidget(separator1);
	this->addWidget(filterAdv);
	this->addWidget(filter);
	this->addWidget(separator2);
	this->addSeparator();
	this->addWidget(separator3);


	connect(gotoToday_but, SIGNAL(clicked()), this, SLOT(gotoToday()));
	connect(gotoNext, SIGNAL(clicked()), this, SLOT(nextDay()));
	connect(gotoPrev, SIGNAL(clicked()), this, SLOT(prevDay()));
	connect(cal, SIGNAL(clicked(QDate)), this, SLOT(dateSelected()));

	connect(filter, SIGNAL(textChanged(QString)), this, SIGNAL(setFilter(QString)));

}
Ejemplo n.º 11
0
void SyntaxHighlighter::loadConfiguration(const QString &filename)
{
    if(filename!="")
    {
        map<QString, QString> attribs;
        QString elem, expr_type, group;
        bool groups_decl=false, chr_sensitive=false,
             bold=false, italic=false,
             underline=false, partial_match=false;
        QTextCharFormat format;
        QRegExp regexp;
        QColor bg_color, fg_color;
        vector<QString>::iterator itr, itr_end;

        try
        {
            clearConfiguration();
            XMLParser::restartParser();
            XMLParser::setDTDFile(GlobalAttributes::CONFIGURATIONS_DIR +
                                  GlobalAttributes::DIR_SEPARATOR +
                                  GlobalAttributes::OBJECT_DTD_DIR +
                                  GlobalAttributes::DIR_SEPARATOR +
                                  GlobalAttributes::CODE_HIGHLIGHT_CONF +
                                  GlobalAttributes::OBJECT_DTD_EXT,
                                  GlobalAttributes::CODE_HIGHLIGHT_CONF);

            XMLParser::loadXMLFile(filename);

            if(XMLParser::accessElement(XMLParser::CHILD_ELEMENT))
            {
                do
                {
                    if(XMLParser::getElementType()==XML_ELEMENT_NODE)
                    {
                        elem=XMLParser::getElementName();

                        if(elem==ParsersAttributes::WORD_SEPARATORS)
                        {
                            XMLParser::getElementAttributes(attribs);
                            word_separators=attribs[ParsersAttributes::VALUE];
                        }
                        else if(elem==ParsersAttributes::WORD_DELIMITERS)
                        {
                            XMLParser::getElementAttributes(attribs);
                            word_delimiters=attribs[ParsersAttributes::VALUE];
                        }
                        else if(elem==ParsersAttributes::IGNORED_CHARS)
                        {
                            XMLParser::getElementAttributes(attribs);
                            ignored_chars=attribs[ParsersAttributes::VALUE];
                        }

                        /*	If the element is what defines the order of application of the groups
                        		highlight in the (highlight-order). Is in this block that are declared
                        		the groups used to highlight the source code. ALL groups
                        		in this block must be declared before they are built
                        		otherwise an error will be triggered. */
                        else if(elem==ParsersAttributes::HIGHLIGHT_ORDER)
                        {
                            //Marks a flag indication that groups are being declared
                            groups_decl=true;
                            XMLParser::savePosition();
                            XMLParser::accessElement(XMLParser::CHILD_ELEMENT);
                            elem=XMLParser::getElementName();
                        }

                        if(elem==ParsersAttributes::GROUP)
                        {
                            XMLParser::getElementAttributes(attribs);
                            group=attribs[ParsersAttributes::NAME];

                            /* If the parser is on the group declaration block and not in the build block
                            	 some validations are made. */
                            if(groups_decl)
                            {
                                //Raises an error if the group was declared before
                                if(find(groups_order.begin(), groups_order.end(), group)!=groups_order.end())
                                {
                                    throw Exception(Exception::getErrorMessage(ERR_REDECL_HL_GROUP).arg(group),
                                                    ERR_REDECL_HL_GROUP,__PRETTY_FUNCTION__,__FILE__,__LINE__);
                                }
                                //Raises an error if the group is being declared and build at the declaration statment (not permitted)
                                else if(attribs.size() > 1 || XMLParser::hasElement(XMLParser::CHILD_ELEMENT))
                                {
                                    throw Exception(Exception::getErrorMessage(ERR_DEF_INV_GROUP_DECL)
                                                    .arg(group).arg(ParsersAttributes::HIGHLIGHT_ORDER),
                                                    ERR_REDECL_HL_GROUP,__PRETTY_FUNCTION__,__FILE__,__LINE__);
                                }

                                groups_order.push_back(group);
                            }
                            //Case the parser is on the contruction block and not in declaration of groups
                            else
                            {
                                //Raises an error if the group is being constructed by a second time
                                if(initial_exprs.count(group)!=0)
                                {
                                    throw Exception(Exception::getErrorMessage(ERR_DEF_DUPLIC_GROUP).arg(group),
                                                    ERR_DEF_DUPLIC_GROUP,__PRETTY_FUNCTION__,__FILE__,__LINE__);
                                }
                                //Raises an error if the group is being constructed without being declared
                                else if(find(groups_order.begin(), groups_order.end(), group)==groups_order.end())
                                {
                                    throw Exception(Exception::getErrorMessage(ERR_DEF_NOT_DECL_GROUP)
                                                    .arg(group).arg(ParsersAttributes::HIGHLIGHT_ORDER),
                                                    ERR_DEF_NOT_DECL_GROUP,__PRETTY_FUNCTION__,__FILE__,__LINE__);
                                }
                                //Raises an error if the group does not have children element
                                else if(!XMLParser::hasElement(XMLParser::CHILD_ELEMENT))
                                {
                                    throw Exception(Exception::getErrorMessage(ERR_DEF_EMPTY_GROUP).arg(group),
                                                    ERR_DEF_EMPTY_GROUP,__PRETTY_FUNCTION__,__FILE__,__LINE__);
                                }

                                chr_sensitive=(attribs[ParsersAttributes::CASE_SENSITIVE]==ParsersAttributes::_TRUE_);
                                italic=(attribs[ParsersAttributes::ITALIC]==ParsersAttributes::_TRUE_);
                                bold=(attribs[ParsersAttributes::BOLD]==ParsersAttributes::_TRUE_);
                                underline=(attribs[ParsersAttributes::UNDERLINE]==ParsersAttributes::_TRUE_);
                                partial_match=(attribs[ParsersAttributes::PARTIAL_MATCH]==ParsersAttributes::_TRUE_);
                                fg_color.setNamedColor(attribs[ParsersAttributes::FOREGROUND_COLOR]);

                                //If the attribute isn't defined the bg color will be transparent
                                if(attribs[ParsersAttributes::BACKGROUND_COLOR].isEmpty())
                                    bg_color.setRgb(0,0,0,0);
                                else
                                    bg_color.setNamedColor(attribs[ParsersAttributes::BACKGROUND_COLOR]);

                                if(!attribs[ParsersAttributes::LOOKAHEAD_CHAR].isEmpty())
                                    lookahead_char[group]=attribs[ParsersAttributes::LOOKAHEAD_CHAR][0];

                                format.setFontItalic(italic);
                                format.setFontUnderline(underline);

                                if(bold)
                                    format.setFontWeight(QFont::Bold);
                                else
                                    format.setFontWeight(QFont::Normal);

                                format.setForeground(fg_color);
                                format.setBackground(bg_color);
                                formats[group]=format;


                                XMLParser::savePosition();
                                XMLParser::accessElement(XMLParser::CHILD_ELEMENT);

                                if(chr_sensitive)
                                    regexp.setCaseSensitivity(Qt::CaseSensitive);
                                else
                                    regexp.setCaseSensitivity(Qt::CaseInsensitive);

                                this->partial_match[group]=partial_match;

                                do
                                {
                                    if(XMLParser::getElementType()==XML_ELEMENT_NODE)
                                    {
                                        XMLParser::getElementAttributes(attribs);
                                        expr_type=attribs[ParsersAttributes::TYPE];
                                        regexp.setPattern(attribs[ParsersAttributes::VALUE]);

                                        if(attribs[ParsersAttributes::REGULAR_EXP]==ParsersAttributes::_TRUE_)
                                            regexp.setPatternSyntax(QRegExp::RegExp2);
                                        else if(attribs[ParsersAttributes::WILDCARD]==ParsersAttributes::_TRUE_)
                                            regexp.setPatternSyntax(QRegExp::Wildcard);
                                        else
                                            regexp.setPatternSyntax(QRegExp::FixedString);

                                        if(expr_type=="" ||
                                                expr_type==ParsersAttributes::SIMPLE_EXP ||
                                                expr_type==ParsersAttributes::INITIAL_EXP)
                                            initial_exprs[group].push_back(regexp);
                                        else
                                            final_exprs[group].push_back(regexp);
                                    }
                                }
                                while(XMLParser::accessElement(XMLParser::NEXT_ELEMENT));
                                XMLParser::restorePosition();
                            }
                        }
                    }

                    /* Check if there are some other groups to be declared, if not,
                    		continues to reading to the other part of configuration */
                    if(groups_decl && !XMLParser::hasElement(XMLParser::NEXT_ELEMENT))
                    {
                        groups_decl=false;
                        XMLParser::restorePosition();
                    }

                }
                while(XMLParser::accessElement(XMLParser::NEXT_ELEMENT));
            }

            itr=groups_order.begin();
            itr_end=groups_order.end();

            while(itr!=itr_end)
            {
                group=(*itr);
                itr++;

                if(initial_exprs[group].size()==0)
                {
                    //Raises an error if the group was declared but not constructed
                    throw Exception(Exception::getErrorMessage(ERR_GROUP_DECL_NOT_DEFINED).arg(group),
                                    ERR_GROUP_DECL_NOT_DEFINED,__PRETTY_FUNCTION__,__FILE__,__LINE__);
                }
            }

            conf_loaded=true;
        }
        catch(Exception &e)
        {
            throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e);
        }
    }
}
Ejemplo n.º 12
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"));

    menuBar()->addMenu(fileMenu);
    editor = new QTextEdit();

    QTextCursor cursor(editor->textCursor());
    cursor.movePosition(QTextCursor::Start);

    QTextFrame *mainFrame = cursor.currentFrame();

    QTextCharFormat plainCharFormat;
    QTextCharFormat boldCharFormat;
    boldCharFormat.setFontWeight(QFont::Bold);
/*  main frame
//! [0]
    QTextFrame *mainFrame = cursor.currentFrame();
    cursor.insertText(...);
//! [0]
*/
    cursor.insertText("Text documents are represented by the "
                      "QTextDocument class, rather than by QString objects. "
                      "Each QTextDocument object contains information about "
                      "the document's internal representation, its structure, "
                      "and keeps track of modifications to provide undo/redo "
                      "facilities. This approach allows features such as the "
                      "layout management to be delegated to specialized "
                      "classes, but also provides a focus for the framework.",
                      plainCharFormat);

//! [1]
    QTextFrameFormat frameFormat;
    frameFormat.setMargin(32);
    frameFormat.setPadding(8);
    frameFormat.setBorder(4);
//! [1]
    cursor.insertFrame(frameFormat);

/*  insert frame
//! [2]
    cursor.insertFrame(frameFormat);
    cursor.insertText(...);
//! [2]
*/
    cursor.insertText("Documents are either converted from external sources "
                      "or created from scratch using Qt. The creation process "
                      "can done by an editor widget, such as QTextEdit, or by "
                      "explicit calls to the Scribe API.", boldCharFormat);

    cursor = mainFrame->lastCursorPosition();
/*  last cursor
//! [3]
    cursor = mainFrame->lastCursorPosition();
    cursor.insertText(...);
//! [3]
*/
    cursor.insertText("There are two complementary ways to visualize the "
                      "contents of a document: as a linear buffer that is "
                      "used by editors to modify the contents, and as an "
                      "object hierarchy containing structural information "
                      "that is useful to layout engines. In the hierarchical "
                      "model, the objects generally correspond to visual "
                      "elements such as frames, tables, and lists. At a lower "
                      "level, these elements describe properties such as the "
                      "style of text used and its alignment. The linear "
                      "representation of the document is used for editing and "
                      "manipulation of the document's contents.",
                      plainCharFormat);


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

    setCentralWidget(editor);
    setWindowTitle(tr("Text Document Frames"));
}
Ejemplo n.º 13
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 accomodate 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 {
                    kDebug() << "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);
}
Ejemplo n.º 14
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"));
}
Ejemplo n.º 15
0
void CreateBlogMsg::changeFormatType(int styleIndex )
{
    ui.msgEdit->setFocus( Qt::OtherFocusReason );

    QTextCursor cursor = ui.msgEdit->textCursor();
    //QTextBlockFormat bformat = cursor.blockFormat();
    QTextBlockFormat bformat;
    QTextCharFormat cformat;

    switch (styleIndex) {
         default:
            case 0:
            bformat.setProperty( TextFormat::HtmlHeading, QVariant( 0 ) );
            cformat.setFontWeight( QFont::Normal );
            cformat.setProperty( QTextFormat::FontSizeAdjustment, QVariant( 0 ) );
            break;
        case 1:
            bformat.setProperty( TextFormat::HtmlHeading, QVariant( 1 ) );
            cformat.setFontWeight( QFont::Bold );
            cformat.setProperty( QTextFormat::FontSizeAdjustment, QVariant( 3 ) );
            break;
        case 2:
            bformat.setProperty( TextFormat::HtmlHeading, QVariant( 2 ) );
            cformat.setFontWeight( QFont::Bold );
            cformat.setProperty( QTextFormat::FontSizeAdjustment, QVariant( 2 ) );
            break;
        case 3:
            bformat.setProperty( TextFormat::HtmlHeading, QVariant( 3 ) );
            cformat.setFontWeight( QFont::Bold );
            cformat.setProperty( QTextFormat::FontSizeAdjustment, QVariant( 1 ) );
            break;
        case 4:
            bformat.setProperty( TextFormat::HtmlHeading, QVariant( 4 ) );
            cformat.setFontWeight( QFont::Bold );
            cformat.setProperty( QTextFormat::FontSizeAdjustment, QVariant( 0 ) );
            break;
        case 5:
            bformat.setProperty( TextFormat::HtmlHeading, QVariant( 5 ) );
            cformat.setFontWeight( QFont::Bold );
            cformat.setProperty( QTextFormat::FontSizeAdjustment, QVariant( -1 ) );
            break;
        case 6:
            bformat.setProperty( TextFormat::HtmlHeading, QVariant( 6 ) );
            cformat.setFontWeight( QFont::Bold );
            cformat.setProperty( QTextFormat::FontSizeAdjustment, QVariant( -2 ) );
            break;
    }
    //cformat.clearProperty( TextFormat::HasCodeStyle );

    cursor.beginEditBlock();
    cursor.mergeBlockFormat( bformat );
    cursor.select( QTextCursor::BlockUnderCursor );
    cursor.mergeCharFormat( cformat );
    cursor.endEditBlock();
}
Ejemplo n.º 16
0
/** "Help message" or "About" dialog box */
HelpMessageDialog::HelpMessageDialog(interfaces::Node& node, QWidget *parent, bool about) :
    QDialog(parent),
    ui(new Ui::HelpMessageDialog)
{
    ui->setupUi(this);

    QString version = tr(PACKAGE_NAME) + " " + 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 ambiguous.
     */
#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 %1").arg(tr(PACKAGE_NAME)));

        /// 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", "<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 = "Usage:  elements-qt [command-line options]                     \n";
        QTextCursor cursor(ui->helpMessage->document());
        cursor.insertText(version);
        cursor.insertBlock();
        cursor.insertText(header);
        cursor.insertBlock();

        std::string strUsage = gArgs.GetHelpMessage();
        QString coreOptions = QString::fromStdString(strUsage);
        text = version + "\n\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);

        for (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);
    }
}
Ejemplo n.º 17
0
void CreateBlogMsg::currentCharFormatChanged(const QTextCharFormat &format)
{
    fontChanged(format.font());
    colorChanged(format.foreground().color());
}
NcBlockHighlighter::NcBlockHighlighter(QTextDocument *parent) : QSyntaxHighlighter(parent)
{

	HighlightingRule rule;

	QTextCharFormat GFormat;
	QTextCharFormat NFormat;
	QTextCharFormat MFormat;
	QTextCharFormat XFormat;
	QTextCharFormat ZFormat;
	QTextCharFormat UFormat;
	QTextCharFormat WFormat;
	QTextCharFormat IFormat;
	QTextCharFormat KFormat;
	QTextCharFormat FFormat;
	QTextCharFormat SFormat;
	QTextCharFormat TFormat;

	GFormat.setFontWeight(QFont::Bold);
	GFormat.setForeground(Qt::darkMagenta);
	QString Gpattern ="\\b[G][0-9]{1,2}\\b";

	rule.pattern = QRegExp(Gpattern);
	rule.format = GFormat;
	highlightingRules.append(rule);


     	
 	NFormat.setFontWeight(QFont::Bold);
 	NFormat.setForeground(Qt::black);
 	QString Npattern = "\\b[N][0-9]{1,4}\\b";
	
 	rule.pattern = QRegExp(Npattern);
	rule.format = NFormat;
	highlightingRules.append(rule);


	MFormat.setFontWeight(QFont::Bold);
    MFormat.setForeground(Qt::darkYellow);
    QString Mpattern = "\\b[M][0-9]{1,3}\\b";

	rule.pattern = QRegExp(Mpattern);
	rule.format = MFormat;
	highlightingRules.append(rule);

	FFormat.setFontWeight(QFont::Bold);
    FFormat.setForeground(Qt::darkBlue);
    QString Fpattern = "\\b[F][0-9]{1,5}\\b";

    rule.pattern = QRegExp(Fpattern);
	rule.format = FFormat;
	highlightingRules.append(rule);


	XFormat.setFontWeight(QFont::Bold);
    XFormat.setForeground(Qt::darkGreen);
	QString Xpattern = "\\b[X][+-]?\\d*\\.?\\d*\\b";

    rule.pattern = QRegExp(Xpattern);
	rule.format = XFormat;
	highlightingRules.append(rule);

	ZFormat.setFontWeight(QFont::Bold);
    ZFormat.setForeground(Qt::darkGreen);
    QString Zpattern = "\\b[Z][+-]?\\d*\\.?\\d*\\b";

    rule.pattern = QRegExp(Zpattern);
	rule.format = ZFormat;
	highlightingRules.append(rule);

	UFormat.setFontWeight(QFont::Bold);
    UFormat.setForeground(Qt::darkCyan);
	QString Upattern = "\\b[U][+-]?\\d*\\.?\\d*\\b";

    rule.pattern = QRegExp(Upattern);
	rule.format = UFormat;
	highlightingRules.append(rule);


	WFormat.setFontWeight(QFont::Bold);
    WFormat.setForeground(Qt::darkCyan);
    QString Wpattern = "\\b[W][+-]?\\d*\\.?\\d*\\b";

	rule.pattern = QRegExp(Wpattern);
	rule.format = WFormat;
	highlightingRules.append(rule);

	SFormat.setFontWeight(QFont::Bold);
 	SFormat.setForeground(Qt::darkBlue);
 	QString Spattern = "\\b[S][0-9]{1,5}\\b";

	rule.pattern = QRegExp(Spattern);
	rule.format = SFormat;
	highlightingRules.append(rule);

	TFormat.setFontWeight(QFont::Bold);
 	TFormat.setForeground(Qt::magenta);
 	QString Tpattern = "\\b[T][0-9]{1,4}\\b";

	rule.pattern = QRegExp(Tpattern);
	rule.format = TFormat;
	highlightingRules.append(rule);


	IFormat.setFontWeight(QFont::Bold);
    IFormat.setForeground(Qt::red);
    QString Ipattern = "\\b[I][+-]?\\d*\\.?\\d*\\b";

	rule.pattern = QRegExp(Ipattern);
	rule.format = IFormat;
	highlightingRules.append(rule);
     	
	KFormat.setFontWeight(QFont::Bold);
    KFormat.setForeground(Qt::red);
    QString Kpattern = "\\b[K][+-]?\\d*\\.?\\d*\\b";

	rule.pattern = QRegExp(Kpattern);
	rule.format = KFormat;
	highlightingRules.append(rule);
}
Ejemplo n.º 19
0
QImage RichTextRenderer::renderText()
{
// 	qDebug()<<itemName()<<"TextBoxWarmingThread::run(): htmlCode:"<<htmlCode;
	//qDebug() << "RichTextRenderer::renderText(): HTML:"<<html();
	//qDebug() << "RichTextRenderer::update(): Update Start...";
 	//qDebug() << "RichTextRenderer::renderText(): \t in thread:"<<QThread::currentThreadId();
	if(m_updateTimer.isActive())
		m_updateTimer.stop();
		
	QTime renderTime;
	renderTime.start();
	
	QTextDocument doc;
	QTextDocument shadowDoc;
	
	if (Qt::mightBeRichText(html()))
	{
		doc.setHtml(html());
		shadowDoc.setHtml(html());
	}
	else
	{
		doc.setPlainText(html());
		shadowDoc.setPlainText(html());
	}
	
	int textWidth = m_textWidth;

	doc.setTextWidth(textWidth);
	shadowDoc.setTextWidth(textWidth);
	
	// Apply outline pen to the html
	QTextCursor cursor(&doc);
	cursor.select(QTextCursor::Document);

	QTextCharFormat format;

	QPen p(Qt::NoPen);
	if(outlineEnabled())
	{
		p = outlinePen();
		p.setJoinStyle(Qt::MiterJoin);
	}

	format.setTextOutline(p);
	//format.setForeground(fillEnabled() ? fillBrush() : Qt::NoBrush); //Qt::white);

	cursor.mergeCharFormat(format);
	
	// Setup the shadow text formatting if enabled
	if(shadowEnabled())
	{
		if(shadowBlurRadius() <= 0.05)
		{
			QTextCursor cursor(&shadowDoc);
			cursor.select(QTextCursor::Document);
	
			QTextCharFormat format;
			format.setTextOutline(Qt::NoPen);
			format.setForeground(shadowBrush());
	
			cursor.mergeCharFormat(format);
		}
	}
	
			
	QSizeF shadowSize = shadowEnabled() ? QSizeF(shadowOffsetX(),shadowOffsetY()) : QSizeF(0,0);
	QSizeF docSize = doc.size();
	QSizeF padSize(12.,12.);
	QSizeF sumSize = (docSize + shadowSize + padSize);//.toSize();
	
	QSizeF scaledSize = QSizeF(sumSize.width() * m_scaling.x(), sumSize.height() * m_scaling.y());
	if(m_scaling.x() != 1. || m_scaling.y() != 1.)
	{
		//qDebug() << "RichTextRenderer::renderText(): Orig size:"<<sumSize<<", scaled size:"<<scaledSize<<", scaling:"<<m_scaling;
		m_rawSize = sumSize;
	}
	//qDebug() << "RichTextRenderer::update(): textWidth: "<<textWidth<<", shadowSize:"<<shadowSize<<", docSize:"<<docSize<<", sumSize:"<<sumSize;
	QImage cache(scaledSize.toSize(),QImage::Format_ARGB32); //_Premultiplied);
	memset(cache.scanLine(0),0,cache.byteCount());
	
	double padSizeHalfX = padSize.width() / 2;
	double padSizeHalfY = padSize.height() / 2;
			
	
	QPainter textPainter(&cache);
	textPainter.scale(m_scaling.x(), m_scaling.y());
	//textPainter.fillRect(cache.rect(),Qt::transparent);
	
	QAbstractTextDocumentLayout::PaintContext pCtx;

	//qDebug() << "RichTextRenderer::renderText(): shadowEnabled():"<<shadowEnabled()<<", shadowBlurRadius():"<<shadowBlurRadius(); 
	if(shadowEnabled())
	{
		if(shadowBlurRadius() <= 0.05)
		{
			// render a "cheap" version of the shadow using the shadow text document
			textPainter.save();

			textPainter.translate(shadowOffsetX(),shadowOffsetY());
			shadowDoc.documentLayout()->draw(&textPainter, pCtx);

			textPainter.restore();
		}
		else
		{
			double radius = shadowBlurRadius();
			
			// create temporary pixmap to hold a copy of the text
			QSizeF blurSize = ImageFilters::blurredSizeFor(doc.size(), (int)radius);
			
			QSizeF scaledBlurSize = QSize(blurSize.width() * m_scaling.x(), blurSize.height() * m_scaling.y());
			//QSize docSize = doc.size();
			//qDebug() << "RichTextRenderer::renderText(): [shadow] radius:"<<radius<<" blurSize:"<<blurSize<<", scaling:"<<m_scaling<<", scaledBlurSize:"<<scaledBlurSize;
			
			
			//qDebug() << "Blur size:"<<blurSize<<", doc:"<<doc.size()<<", radius:"<<radius;
			QImage tmpImage(scaledBlurSize.toSize(),QImage::Format_ARGB32_Premultiplied);
			memset(tmpImage.scanLine(0),0,tmpImage.byteCount());
			
			// render the text
			QPainter tmpPainter(&tmpImage);
			tmpPainter.scale(m_scaling.x(), m_scaling.y());
			
			tmpPainter.save();
			tmpPainter.translate(radius + padSizeHalfX, radius + padSizeHalfY);
			doc.documentLayout()->draw(&tmpPainter, pCtx);
			tmpPainter.restore();
			
			// blacken the text by applying a color to the copy using a QPainter::CompositionMode_DestinationIn operation. 
			// This produces a homogeneously-colored pixmap.
			QRect rect = tmpImage.rect();
			tmpPainter.setCompositionMode(QPainter::CompositionMode_SourceIn);
			tmpPainter.fillRect(rect, shadowBrush().color());
			tmpPainter.end();

			// blur the colored text
			ImageFilters::blurImage(tmpImage, (int)radius);
			
			// render the blurred text at an offset into the cache
			textPainter.save();
			textPainter.translate(shadowOffsetX() - radius,
					      shadowOffsetY() - radius);
			textPainter.drawImage(0, 0, tmpImage);
			textPainter.restore();
		}
	}
	
	textPainter.translate(padSizeHalfX, padSizeHalfY);
	doc.documentLayout()->draw(&textPainter, pCtx);
	
	textPainter.end();
	
	m_image = cache.convertToFormat(QImage::Format_ARGB32);
	emit textRendered(m_image);
	
	//qDebug() << "RichTextRenderer::renderText(): Render finished, elapsed:"<<renderTime.elapsed()<<"ms";
	//m_image.save("debug-text.png");
	return m_image;
	
}
Ejemplo n.º 20
0
bool MakeStep::init()
{
    Qt4BuildConfiguration *bc = qt4BuildConfiguration();
    Environment environment = bc->environment();
    setEnvironment(environment);

    QString workingDirectory;
    if (bc->subNodeBuild())
        workingDirectory = bc->subNodeBuild()->buildDir();
    else
        workingDirectory = bc->buildDirectory();
    setWorkingDirectory(workingDirectory);

    QString makeCmd = bc->makeCommand();
    if (!m_makeCmd.isEmpty())
        makeCmd = m_makeCmd;
    if (!QFileInfo(makeCmd).isAbsolute()) {
        // Try to detect command in environment
        const QString tmp = environment.searchInPath(makeCmd);
        if (tmp.isEmpty()) {
            QTextCharFormat textCharFormat;
            textCharFormat.setForeground(Qt::red);
            emit addOutput(tr("Could not find make command: %1 in the build environment").arg(makeCmd), textCharFormat);
            return false;
        }
        makeCmd = tmp;
    }
    setCommand(makeCmd);

    // If we are cleaning, then make can fail with a error code, but that doesn't mean
    // we should stop the clean queue
    // That is mostly so that rebuild works on a already clean project
    setIgnoreReturnValue(m_clean);
    QStringList args = m_userArgs;
    if (!m_clean) {
        if (!bc->defaultMakeTarget().isEmpty())
            args << bc->defaultMakeTarget();
    }
    // -w option enables "Enter"/"Leaving directory" messages, which we need for detecting the
    // absolute file path
    // FIXME doing this without the user having a way to override this is rather bad
    // so we only do it for unix and if the user didn't override the make command
    // but for now this is the least invasive change
    ProjectExplorer::ToolChain *toolchain = bc->toolChain();

    if (toolchain) {
        if (toolchain->type() != ProjectExplorer::ToolChain::MSVC &&
            toolchain->type() != ProjectExplorer::ToolChain::WINCE) {
            if (m_makeCmd.isEmpty())
                args << "-w";
        }
    }

    setEnabled(true);
    setArguments(args);

    setOutputParser(new ProjectExplorer::GnuMakeParser(workingDirectory));
    if (toolchain)
        appendOutputParser(toolchain->outputParser());

    return AbstractProcessStep::init();
}
Ejemplo n.º 21
0
void GrepOutputDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const
{ 
    // there is no function in QString to left-trim. A call to remove this this regexp does the job
    static const QRegExp leftspaces("^\\s*", Qt::CaseSensitive, QRegExp::RegExp);
    
    // rich text component
    const GrepOutputModel *model = dynamic_cast<const GrepOutputModel *>(index.model());
    const GrepOutputItem  *item  = dynamic_cast<const GrepOutputItem *>(model->itemFromIndex(index));

    QStyleOptionViewItemV4 options = option;
    initStyleOption(&options, index);

    // building item representation
    QTextDocument doc;
    QTextCursor cur(&doc);
    
    QPalette::ColorGroup cg = options.state & QStyle::State_Enabled
                                ? QPalette::Normal : QPalette::Disabled;
    QPalette::ColorRole cr  = options.state & QStyle::State_Selected
                                ? QPalette::HighlightedText : QPalette::Text;
    QTextCharFormat fmt = cur.charFormat();
    fmt.setFont(options.font);

    if(item && item->isText())
    {
        // Use custom manual highlighting

        const KTextEditor::Range rng = item->change()->m_range;

        // the line number appears grayed
        fmt.setForeground(options.palette.brush(QPalette::Disabled, cr));
        cur.insertText(i18n("Line %1: ",item->lineNumber()), fmt);
        
        // switch to normal color
        fmt.setForeground(options.palette.brush(cg, cr));
        cur.insertText(item->text().left(rng.start().column()).remove(leftspaces), fmt);
        
        fmt.setFontWeight(QFont::Bold);
        // Blend the highlighted background color
        // For some reason, it is extremely slow to use alpha-blending directly here
        QColor bgHighlight = blendColor(option.palette.brush(QPalette::Highlight).color(), option.palette.brush(QPalette::Base).color(), 0.3);
        fmt.setBackground(bgHighlight);
        cur.insertText(item->text().mid(rng.start().column(), rng.end().column() - rng.start().column()), fmt);
        fmt.clearBackground();
        
        fmt.setFontWeight(QFont::Normal);
        cur.insertText(item->text().right(item->text().length() - rng.end().column()), fmt);
    }else{
        QString text;
        if(item)
            text = item->text();
        else
            text = index.data().toString();
        // Simply insert the text as html. We use this for the titles.
        doc.setHtml(text);
    }
    
    painter->save();
    options.text = QString();  // text will be drawn separately
    options.widget->style()->drawControl(QStyle::CE_ItemViewItem, &options, painter, options.widget);

    // set correct draw area
    QRect clip = options.widget->style()->subElementRect(QStyle::SE_ItemViewItemText, &options);
    QFontMetrics metrics(options.font);
    painter->translate(clip.topLeft() - QPoint(0, metrics.descent()));

    // We disable the clipping for now, as it leads to strange clipping errors
//     clip.setTopLeft(QPoint(0,0));
    
//     painter->setClipRect(clip);
    QAbstractTextDocumentLayout::PaintContext ctx;
//     ctx.clip = clip;
    painter->setBackground(Qt::transparent);
    doc.documentLayout()->draw(painter, ctx);

    painter->restore();
}
Ejemplo n.º 22
0
void CreateBlogMsg::textBold()
{
    QTextCharFormat fmt;
    fmt.setFontWeight(actionTextBold->isChecked() ? QFont::Bold : QFont::Normal);
    mergeFormatOnWordOrSelection(fmt);
}
Ejemplo n.º 23
0
Config::Config(QObject* parent)
    : QSettings(ORGNAME, PROGNAME, parent)
{
    keywordsSorted = keywords.keywords.values();
    keywordsSorted.sort();

    languages.insert("English", "en_EN");
    languages.insert("Russian", "ru_RU");

    maxRecentFiles = 9;
    maxHistory 	   = 10;

    beginGroup("General");
    language    	   = value("language", "English").toString();
    recentFiles 	   = value("recentFiles").toStringList();
    openFiles   	   = value("openFiles").toStringList();
    lastFile  		   = value("lastFile").toString();
    mainWindowGeometry = value("mainWindowGeometry").toByteArray();
    mainWindowState    = value("mainWindowState").toByteArray();
    helpWindowGeometry = value("helpWindowGeometry").toByteArray();
    endGroup();

    beginGroup("Editor");
    fontFamily   = value("fontFamily", "Courier New").toString();
    fontSize     = value("fontSize", 12).toInt();
    tabIndents   = value("tabIndents").toBool();
    autoIndent   = value("autoIndent").toBool();
    backUnindent = value("backUnindent").toBool();
    spaceTabs    = value("spaceTabs", true).toBool();
    indentSize   = value("indentSize", 4).toInt();
    tabSize      = value("tabSize", 4).toInt();
    whitespaces  = value("whitespaces").toBool();

    QTextCharFormat fmt; // формат по умолчанию, не изменяется
    fmt.setBackground(QColor(255, 255, 255, 0)) ; // прозрачный белый

    int size = beginReadArray("ColorScheme");

    for (int i = 0; i < size; i++) {
        setArrayIndex(i);

        QString type = value("type").toString();

        colorScheme.insert(type, fmt);
        colorScheme[type].setFontItalic(value("italic").toBool());
        colorScheme[type].setFontWeight(value("weihgt").toInt());
        colorScheme[type].setForeground(value("foreground").value<QColor>());
        colorScheme[type].setBackground(value("background").value<QColor>());
    }

    endArray();

    QHashIterator<QString, QString> it(keywords.keywords);

    while (it.hasNext()) {
        it.next();

        QString keyword = it.value();

        keyword.replace("*", "\\*").replace("$", "\\$");
        patterns.insert(it.key(), QRegExp(tr("\\b%1\\b").arg(keyword)));

        if (!colorScheme.contains(it.key())) // для всех слов пустая схема при size == 0
            colorScheme.insert(it.key(), fmt);
    }

    // 1. для неключевых слов добавить шаблон
    patterns.insert("Parentheses", 	    QRegExp("[\\(\\)\\[\\]]"));
    patterns.insert("Numbers", 			QRegExp("(^|\\s)[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?"));
    patterns.insert("Local Variables",  QRegExp("\\$?\\?[\\w-]+"));
    patterns.insert("Global Variables", QRegExp("\\?\\*[\\w-]+\\*"));

    // 2. настроить схему по умолчанию
    if (!size) {
        colorScheme.insert("Constructs", fmt);
        colorScheme["Constructs"].setFontWeight(QFont::Bold);
        colorScheme["Constructs"].setForeground(Qt::darkBlue);

        colorScheme.insert("Strings", fmt);
        colorScheme["Strings"].setForeground(Qt::darkRed);

        colorScheme.insert("Comments", fmt);
        colorScheme["Comments"].setFontItalic(true);
        colorScheme["Comments"].setForeground(Qt::darkGreen);

        colorScheme.insert("Parentheses", fmt);
        colorScheme["Parentheses"].setFontWeight(QFont::Bold);

        colorScheme.insert("Numbers", fmt);
        colorScheme["Numbers"].setForeground(Qt::darkYellow);

        colorScheme.insert("Local Variables", fmt);
        colorScheme["Local Variables"].setForeground(Qt::darkYellow);

        colorScheme.insert("Global Variables", fmt);
        colorScheme["Global Variables"].setForeground(Qt::darkYellow);

        colorScheme.insert("Text", fmt);
        colorScheme["Text"].setForeground(Qt::black);
        colorScheme["Text"].setBackground(Qt::white);

        colorScheme.insert("Line Numbers", fmt);
        colorScheme["Line Numbers"].setForeground(Qt::gray);
        colorScheme["Line Numbers"].setBackground(QColor(30, 60, 90));
    }

    endGroup(); // Editor

    beginGroup("Sessions");
    leaveOpen       = value("leaveOpen").toBool();
    sessions 	    = value("sessions").toMap();
    sessionSplitter	= value("sessionSplitter").toByteArray();
    endGroup();

    beginGroup("Snippets");
    snippetPath		= value("snippetPath").toString();
    snippetSplitter = value("snippetSplitter").toByteArray();
    endGroup();

    beginGroup("SearchReplace");
    findHistory     = value("findHistory").toStringList();
    replaceHistory  = value("replaceHistory").toStringList();
    matchCase       = value("matchCase").toBool();
    regExp          = value("regExp").toBool();
    allFiles        = value("allFiles").toBool();
    endGroup();
}
Ejemplo n.º 24
0
void CreateBlogMsg::textUnderline()
{
    QTextCharFormat fmt;
    fmt.setFontUnderline(actionTextUnderline->isChecked());
    mergeFormatOnWordOrSelection(fmt);
}
Ejemplo n.º 25
0
void MailEditorMainWindow::onCurrentCharFormatChanged(const QTextCharFormat &format)
  {
  fontChanged(format.font());
  colorChanged(format.foreground().color());
  }
Ejemplo n.º 26
0
void CreateBlogMsg::textItalic()
{
    QTextCharFormat fmt;
    fmt.setFontItalic(actionTextItalic->isChecked());
    mergeFormatOnWordOrSelection(fmt);
}
Ejemplo n.º 27
0
void MailEditorMainWindow::onTextItalicTriggerred(bool checked)
  {
  QTextCharFormat fmt;
  fmt.setFontItalic(checked);
  mergeFormatOnWordOrSelection(fmt);
  }
Ejemplo n.º 28
0
void CreateBlogMsg::textFamily(const QString &f)
{
    QTextCharFormat fmt;
    fmt.setFontFamily(f);
    mergeFormatOnWordOrSelection(fmt);
}
Ejemplo n.º 29
0
void MainWindow::formatQuestions(const PACKEDQUESTIONS &qset)
{

    TestAssistance *pt = TestAssistance::get();
    QTextEdit *pEdit = textEditor.editor;
    QTextCursor cursor = pEdit->textCursor();

    //set alignment center
    pEdit->setAlignment(Qt::AlignHCenter);
    groupCheck(0);

    //set font of title and info
    QFont font = pEdit->font();
    QTextCharFormat fmt;
    font.setBold(true);
    font.setPointSize(14);
    fmt.setFont(font);
    cursor.select(QTextCursor::BlockUnderCursor);
    cursor.mergeCharFormat(fmt);

    //insert school name
    cursor.insertText(tr("%1\n").arg(pt->getPaperInfo().strSchool));

    //insert title
    cursor.insertText(tr("“%1”专业(学院) 2011—2012学年第一学期\n").arg(pt->getPaperInfo().major));


    //insert paper info
    cursor.insertText(tr("《%1》期末考试试卷(%2卷) 考核形式(%3卷)\n").arg(pt->getPaperInfo().strCourse)
                      .arg(pt->getPaperInfo().strPaperType).arg(((pt->getPaperInfo().bOpenOrClose)?"开":"闭")));

    //insert author
    cursor.insertText(tr("作者:%1\n").arg(pt->getPaperInfo().strAuthor));

    pEdit->setTextCursor(cursor);

    //set alignment left
    pEdit->setAlignment(Qt::AlignLeft);
    groupCheck(2);

    //get judge
    QString text;
    int type = 0;

    const std::vector<QUESTION> &j = qset.judge;
    if(!j.empty()){
        insertQuestionTypeTitle(tr("%1.判断题").arg(digitToChinese(type+1)));
        type++;

        for(size_t i = 0; i != j.size(); ++i){
            cursor.insertText(tr("%1.").arg(i+1) + j[i].txt + "\n");
            if(!j[i].imgBytes.isEmpty()){
                QImage img;
                img.loadFromData(j[i].imgBytes, "PNG");
                cursor.insertImage(img);
                cursor.insertText("\n\n");
            }
            pEdit->setTextCursor(cursor);
        }
    }

    //get choice
    text.clear();
    const std::vector<QUESTION> &c = qset.choice;
    if(!c.empty()){
        insertQuestionTypeTitle(tr("%1.选择题").arg(digitToChinese(type+1)));
        type++;

        for(size_t i = 0; i != c.size(); ++i){
            cursor.insertText(tr("%1.").arg(i+1) + c[i].txt + "\n");
            if(!c[i].imgBytes.isEmpty()){
                QImage img;
                img.loadFromData(c[i].imgBytes, "PNG");
                cursor.insertImage(img);
                cursor.insertText("\n\n");
            }
            else
                cursor.insertText("\n");
            pEdit->setTextCursor(cursor);
        }
    }

    //get fill
    text.clear();
    const std::vector<QUESTION> &f = qset.fill;
    if(!f.empty()){
        insertQuestionTypeTitle(tr("%1.填空题").arg(digitToChinese(type+1)));
        type++;

        for(size_t i = 0; i != f.size(); ++i){
            cursor.insertText(tr("%1.").arg(i+1) + f[i].txt + "\n");
            if(!f[i].imgBytes.isEmpty()){
                QImage img;
                img.loadFromData(f[i].imgBytes, "PNG");
                cursor.insertImage(img);
                cursor.insertText("\n\n");
            }
            pEdit->setTextCursor(cursor);
        }
    }

    //get calc
    text.clear();
    const std::vector<QUESTION> &l = qset.calc;
    if(!l.empty()){
        insertQuestionTypeTitle(tr("%1.计算题").arg(digitToChinese(type+1)));
        type++;

        for(size_t i = 0; i != l.size(); ++i){
            cursor.insertText(tr("%1.").arg(i+1) + l[i].txt + "\n");
            if(!l[i].imgBytes.isEmpty()){
                QImage img;
                img.loadFromData(l[i].imgBytes, "PNG");
                cursor.insertImage(img);
                cursor.insertText("\n\n");
            }
            pEdit->setTextCursor(cursor);
        }
    }

    //get ans
    text.clear();
    const std::vector<QUESTION> &a = qset.ans;
    if(!a.empty()){
        insertQuestionTypeTitle(tr("%1.问答题").arg(digitToChinese(type+1)));
        type++;

        for(size_t i = 0; i != a.size(); ++i){
            cursor.insertText(tr("%1.").arg(i+1) + a[i].txt + "\n");
            if(!a[i].imgBytes.isEmpty()){
                QImage img;
                img.loadFromData(a[i].imgBytes, "PNG");
                cursor.insertImage(img);
                cursor.insertText("\n\n");
            }
            else
                cursor.insertText("\n");
            pEdit->setTextCursor(cursor);
        }
    }
}
Ejemplo n.º 30
0
void TextEditor::fontChanged(const QFont& f)
      {
      QTextCharFormat cf = edit->currentCharFormat();
      cf.setFontFamily(f.family());
      edit->setCurrentCharFormat(cf);
      }