当前位置: 首页>>代码示例>>C++>>正文


C++ QTextBlock类代码示例

本文整理汇总了C++中QTextBlock的典型用法代码示例。如果您正苦于以下问题:C++ QTextBlock类的具体用法?C++ QTextBlock怎么用?C++ QTextBlock使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了QTextBlock类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: initForNewTest

void TestDocumentLayout::testNumberedList()
{
    initForNewTest("Base\nListItem1\nListItem2\nListItem3\nListItem4\nListItem5\nListItem6\nListItem6\nListItem7\nListItem8\nListItem9\nListItem10\nListItem11\nListItem12\n");

    KoParagraphStyle style;
    m_styleManager->add(&style);
    QTextBlock block = m_doc->begin();
    style.applyStyle(block);
    block = block.next();

    KoListStyle listStyle;
    KoListLevelProperties llp;
    llp.setStyle(KoListStyle::DecimalItem);
    listStyle.setLevelProperties(llp);
    style.setListStyle(&listStyle);

    QTextList *previous = 0;
    int i;
    for (i = 1; i <= 9; i++) {
        QVERIFY(block.isValid());
        // qDebug() << "->" << block.text();
        style.applyStyle(block);
        QTextList *textList = block.textList();
        QVERIFY(textList);
        if (previous == 0) {
            previous = textList;
        } else {
            QCOMPARE(textList, previous);
        }
        QCOMPARE(textList->format().intProperty(QTextListFormat::ListStyle), (int)(KoListStyle::DecimalItem));
        block = block.next();
    }
    m_layout->layout();
    QTextLayout *blockLayout = m_block.layout();

    QCOMPARE(blockLayout->lineAt(0).x(), 0.0);
    QTextBlock blok = m_doc->begin().next();
    qreal indent = blok.layout()->lineAt(0).x();
    QVERIFY(indent > 0.0);
    for (i = 1; i <= 9; ++i) {
        // qDebug() << "=>" << blok.text();
        QTextList *textList = blok.textList();
        QVERIFY(textList);
        QCOMPARE(blok.layout()->lineAt(0).x(), indent); // all the same indent.
        blok = blok.next();
    }

    // now make number of listitems be more than 10, so we use 2 digits.
    for (i = 9; i <= 12; ++i) {
        QVERIFY(block.isValid());
        style.applyStyle(block);
        // qDebug() << "->" << block.text();
        block = block.next();
    }
    m_layout->layout();
    blockLayout = m_block.layout();

    QCOMPARE(blockLayout->lineAt(0).x(), 0.0);
    blok = m_doc->begin().next();
    qreal indent2 = blok.layout()->lineAt(0).x();
    QVERIFY(indent2 > indent); // since it takes an extra digit
    for (i = 2; i <= 12; ++i) {
        // qDebug() << "=>" << blok.text();
        QCOMPARE(blok.layout()->lineAt(0).x(), indent2); // all the same indent.
        blok = blok.next();
    }

    // now to make sure the text is actually properly set.
    block = m_doc->begin().next();
    i = 1;
    while (block.isValid() && i < 13) {
        KoTextBlockData *data = dynamic_cast<KoTextBlockData *>(block.userData());
        QVERIFY(data);
        QCOMPARE(data->counterText(), QString::number(i++));
        block = block.next();
    }

    llp.setListItemSuffix(".");
    llp.setStartValue(4);
    listStyle.setLevelProperties(llp);

    QTextCursor cursor(m_doc);
    cursor.setPosition(10); // listItem1
    QTextBlockFormat format = cursor.blockFormat();
    format.setProperty(KoParagraphStyle::ListStartValue, 4);
    cursor.setBlockFormat(format);

    cursor.setPosition(40); // listItem4
    format = cursor.blockFormat();
    format.setProperty(KoParagraphStyle::ListStartValue, 12);
    cursor.setBlockFormat(format);

    // at this point we start numbering at 4. Have 4, 5, 6, 12, 13, 14, 15 etc
    m_layout->layout();

    // now to make sur the text is actually properly set.
    block = m_doc->begin().next();
    i = 4;
    while (block.isValid() && i < 22) {
        if (i == 7) {
//.........这里部分代码省略.........
开发者ID:HOST-Oman,项目名称:krita,代码行数:101,代码来源:TestLists.cpp

示例2: remove

/*!
    Makes the given \a block part of the list.

    \sa remove(), removeItem()
*/
void QTextList::add(const QTextBlock &block)
{
    QTextBlockFormat fmt = block.blockFormat();
    fmt.setObjectIndex(objectIndex());
    block.docHandle()->setBlockFormat(block, block, fmt, QTextDocumentPrivate::SetFormat);
}
开发者ID:SchleunigerAG,项目名称:WinEC7_Qt5.3.1_Fixes,代码行数:11,代码来源:qtextlist.cpp

示例3: qDebug

void HGMarkdownHighlighter::highlight()
{
    if (cached_elements == NULL) {
        qDebug() << "cached_elements is NULL";
        return;
    }

    if (highlightingStyles == NULL)
        this->setDefaultStyles();

    this->clearFormatting();

    for (int i = 0; i < highlightingStyles->size(); i++)
    {
        HighlightingStyle style = highlightingStyles->at(i);
        pmh_element *elem_cursor = cached_elements[style.type];
        while (elem_cursor != NULL)
        {
            if (elem_cursor->end <= elem_cursor->pos) {
                elem_cursor = elem_cursor->next;
                continue;
            }

            // "The QTextLayout object can only be modified from the
            // documentChanged implementation of a QAbstractTextDocumentLayout
            // subclass. Any changes applied from the outside cause undefined
            // behavior." -- we are breaking this rule here. There might be
            // a better (more correct) way to do this.

            int startBlockNum = document->findBlock(elem_cursor->pos).blockNumber();
            int endBlockNum = document->findBlock(elem_cursor->end).blockNumber();
            for (int j = startBlockNum; j <= endBlockNum; j++)
            {
                QTextBlock block = document->findBlockByNumber(j);

                QTextLayout *layout = block.layout();
                QList<QTextLayout::FormatRange> list = layout->additionalFormats();
                int blockpos = block.position();
                QTextLayout::FormatRange r;
                r.format = style.format;

                if (j == startBlockNum) {
                    r.start = elem_cursor->pos - blockpos;
                    r.length = (startBlockNum == endBlockNum)
                                ? elem_cursor->end - elem_cursor->pos
                                : block.length() - r.start;
                } else if (j == endBlockNum) {
                    r.start = 0;
                    r.length = elem_cursor->end - blockpos;
                } else {
                    r.start = 0;
                    r.length = block.length();
                }

                list.append(r);
                layout->setAdditionalFormats(list);
            }

            elem_cursor = elem_cursor->next;
        }
    }

    document->markContentsDirty(0, document->characterCount());
}
开发者ID:rentzsch,项目名称:peg-markdown-highlight,代码行数:64,代码来源:highlighter.cpp

示例4: getText

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.startsWith(QLatin1String("emoji://e."))) {
							if (EmojiPtr emoji = emojiFromUrl(imageName)) {
								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;
}
开发者ID:AarashFarahani,项目名称:tdesktop,代码行数:76,代码来源:flattextarea.cpp

示例5: Q_ASSERT

QByteArray QGithubMarkdown::write(QTextDocument *source)
{
	QStringList output;
	bool wasInList = false;
	bool inCodeBlock = false;
	auto endCodeBlock = [&]()
	{
		if (inCodeBlock)
		{
			output.append("```\n");
		}
		inCodeBlock = false;
	};
	auto formatForPos = [&](const QTextBlock &block, const int pos) -> QTextCharFormat
	{
		for (const auto fmtRange : block.textFormats())
		{
			if (fmtRange.start <= pos && pos <= (fmtRange.start + fmtRange.length))
			{
				return fmtRange.format;
			}
		}
		Q_ASSERT(false);
		return QTextCharFormat();
	};
	auto blockToMarkdown = [&](const QTextBlock &block, const int offset = 0) -> QString
	{
		QString out;
		bool inBold = false;
		bool inItalic = false;
		QString currentLink;
		for (int i = offset; i < block.text().size(); ++i)
		{
			const QChar c = block.text().at(i);
			const QTextCharFormat fmt = formatForPos(block, i);
			if (fmt.fontItalic() != inItalic)
			{
				out.insert(out.size() - 1, '_');
				inItalic = !inItalic;
			}
			if ((fmt.fontWeight() == QFont::Bold) != inBold)
			{
				out.insert(out.size() - 1, "**");
				inBold = !inBold;
			}
			if (fmt.anchorHref().isEmpty() && !currentLink.isNull())
			{
				out.insert(out.size() - 1, "](" + currentLink + ")");
			}
			else if (!fmt.anchorHref().isEmpty() && currentLink.isNull())
			{
				out.insert(out.size() - 1, "[");
				currentLink = fmt.anchorHref();
			}
			// FIXME images
			out.append(c);
		}
		return out;
	};
	for (QTextBlock block = source->begin(); block != source->end(); block = block.next())
	{
		// heading
		if (block.charFormat().toolTip() == block.text())
		{
			endCodeBlock();
			output.append(QString(sizeMap.key(block.charFormat().fontPointSize()), '#') + " " + block.text() + "\n");
		}
		else
		{
			// list
			if (QTextList *list = block.textList())
			{
				endCodeBlock();
				const QString indent = QString((list->format().indent()-1) * 2, ' ');
				if (list->format().style() == QTextListFormat::ListDisc)
				{
					output.append(indent + "* " + blockToMarkdown(block));
				}
				else
				{
					output.append(indent + QString::number(list->itemNumber(block) + 1) + ". " + blockToMarkdown(block));
				}
				wasInList = true;
			}
			else
			{
				if (wasInList)
				{
					output.append("");
					wasInList = false;
				}
				if (block.charFormat().fontFamily() == "Monospace")
				{
					if (!inCodeBlock)
					{
						inCodeBlock = true;
						output.insert(output.size() - 1, "```");
					}
					output.append(block.text().remove("\n"));
				}
//.........这里部分代码省略.........
开发者ID:02JanDal,项目名称:QMarkdown,代码行数:101,代码来源:QMarkdown.cpp

示例6: switch

void CodeArea::keyPressEvent(QKeyEvent *e)
{

    if (mCompleter && mCompleter->popup()->isVisible())
    {
             // The following keys are forwarded by the completer to the widget
            switch (e->key())
            {
                case Qt::Key_Enter:
                case Qt::Key_Return:
                case Qt::Key_Escape:
                case Qt::Key_Tab:
                case Qt::Key_Backtab:
                     e->ignore();
                     return; // let the completer do default behavior
                default:
                    break;
            }
    }

    {
       switch (e->key()) {
       case Qt::Key_Tab:
       {
           QTextCursor tc = textCursor();
           if(tc.hasSelection())
           {

           }
           if(!(e->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier)))
           {
               this->insertPlainText("    ");
               QTextCursor tc = textCursor();
               tc.setPosition(tc.position());
               setTextCursor(tc);
               return;
           }

       }
       case Qt::Key_Backtab:
       {
           QTextCursor tc = textCursor();

           QTextBlock tb = tc.block();
           QString str = tb.text();
           int space = 4;
           tc.movePosition(QTextCursor::StartOfLine);
           foreach(QString s, str)
           {
               if(s == " "&& space!=0)
               {
                   space--;
                   tc.movePosition(QTextCursor::Right);
                   tc.deletePreviousChar();

               }
               else
                   break;
           }
           return;
       }
       case Qt::Key_Return:
       {
           QTextCursor tc = textCursor();
           QTextBlock tb = tc.block();
           QString str = tb.text();
           int space = 0;
           foreach(QString s, str)
           {
               if(s == " ")
                   space++;
               else
                   break;
           }
           insertPlainText("\n");
           for(int x= 0; x <space;++x)
               insertPlainText(" ");
           tc.movePosition(QTextCursor::EndOfLine);
           setTextCursor(tc);
           e->accept();
           return;
       }
       default:
           break;
       }
    }

    bool isShortcut = ((e->modifiers() & Qt::ControlModifier) && e->key() == Qt::Key_Space); // CTRL+E
    if (!mCompleter || !isShortcut) // do not process the shortcut when we have a completer
        QPlainTextEdit::keyPressEvent(e);

    const bool ctrlOrShift = e->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier);
    if (!mCompleter || (ctrlOrShift && e->text().isEmpty()))
        return;

    static QString eow("[email protected]#$%^&*_+(){}|\"<>?,:./;'[]\\-="); // end of word
    bool hasModifier = (e->modifiers() != Qt::NoModifier) && !ctrlOrShift;
    QString completionPrefix = textUnderCursor();
    /*if(completionPrefix.endsWith(")"))
    {
//.........这里部分代码省略.........
开发者ID:greeduomacro,项目名称:HardUO,代码行数:101,代码来源:CodeArea.cpp

示例7: p

void QFCompleterTextEditNumberBar::paintEvent(QPaintEvent */*event*/) {
    QTextDocument* doc=editor->document();
    QAbstractTextDocumentLayout *layout = doc->documentLayout();
    qreal yPosition=editor->verticalScrollBar()->value();
    qreal vpHeight=editor->viewport()->height();

    QPainter p(this);
    p.setFont(linenumberFont);
    int linenumberWidth=QString::number(doc->blockCount()).size()*p.fontMetrics().width("0")+4;
    int markerheight=p.fontMetrics().ascent()+2;

    // set the width of the widget
    setFixedWidth(linenumberWidth+markerWidth+2);

    // first we draw the background
    p.setBrush(QBrush(linenumberColumnColor));
    p.setPen(QPen(linenumberColumnColor));
    p.drawRect(0,0,width(),vpHeight);
    p.setPen(QPen(markerColumnColor));
    p.setBrush(QBrush(markerColumnColor));
    p.drawRect(linenumberWidth,0,width()-linenumberWidth,vpHeight);

    // reset the rect of all markers
    QMutableMapIterator<int, itemData> i(markers);
    while (i.hasNext()) {
        i.next();
        itemData d=i.value();
        d.rect=QRect(0,0,0,0);
        i.setValue(d);
    }

    // now we draw the line numbers
    p.setPen(QPen(linenumberColor));
    for (QTextBlock it = doc->begin(); it != doc->end(); it = it.next()) {
        QRectF brect=layout->blockBoundingRect(it);
        qreal bottompos=brect.y()+brect.height();
        markerheight=brect.height()-8;
        // we end this loop if the current block lies below the viewport
        if (brect.y() > yPosition+ vpHeight)
            break;
        // if we are inside the viewport, we have to paint a line number for this line
        if (bottompos >= yPosition) {
            QString txt = QString::number(it.blockNumber()+1);
            p.drawText(1, brect.y()-yPosition, linenumberWidth-2, brect.height(), Qt::AlignRight|Qt::AlignVCenter, txt);
            if (markers.contains(it.blockNumber()+1)) {
                itemData d=markers[it.blockNumber()+1];
                QRect markerrect=QRect(linenumberWidth+2, brect.y()-yPosition+4, width()-linenumberWidth-4, markerheight);
                markers[it.blockNumber()+1].rect=markerrect;
                if (d.type==mtInfo) {
                    //p.drawImage(linenumberWidth+2, brect.y()-yPosition, QIcon(":/event_info.png"));
                    p.setBrush(infoMarkerColor);
                    QPen pe=p.pen();
                    pe.setColor(QColor("black"));
                    pe.setCosmetic(true);
                    pe.setWidth(1);
                    p.setPen(pe);
                    p.drawRect(markerrect);
                } else if (d.type==mtError) {
                    //p.drawImage(linenumberWidth+2, brect.y()-yPosition, QIcon(":/event_error.png"));
                    p.setBrush(errorMarkerColor);
                    QPen pe=p.pen();
                    pe.setColor(QColor("black"));
                    pe.setCosmetic(true);
                    pe.setWidth(1);
                    p.setPen(pe);
                    p.drawRect(markerrect);
                } else {
                    //p.drawImage(linenumberWidth+2, brect.y()-yPosition, QIcon(":/event_warning.png"));
                    p.setBrush(warningMarkerColor);
                    QPen pe=p.pen();
                    pe.setColor(QColor("black"));
                    pe.setCosmetic(true);
                    pe.setWidth(1);
                    p.setPen(pe);
                    p.drawRect(markerrect);
                }
            }
        }
    }

}
开发者ID:jkriege2,项目名称:QuickFit3,代码行数:81,代码来源:qfcompletertextedit.cpp

示例8: plt

void GenericCodeEditor::paintLineIndicator( QPaintEvent *e )
{
    QPalette plt( mLineIndicator->palette() );
    QRect r( e->rect() );
    QPainter p( mLineIndicator );

    p.fillRect( r, plt.color( QPalette::Mid ) );
    p.setPen( plt.color(QPalette::Dark) );
    p.drawLine( r.topRight(), r.bottomRight() );

    p.setPen( plt.color(QPalette::ButtonText) );

    QTextDocument *doc = QPlainTextEdit::document();
    QTextCursor cursor(textCursor());
    int selStartBlock, selEndBlock;
    if (cursor.hasSelection()) {
        selStartBlock = doc->findBlock(cursor.selectionStart()).blockNumber();
        selEndBlock = doc->findBlock(cursor.selectionEnd()).blockNumber();
    }
    else
        selStartBlock = selEndBlock = -1;

    QTextBlock block = firstVisibleBlock();
    int blockNumber = block.blockNumber();
    qreal top = blockBoundingGeometry(block).translated(contentOffset()).top();
    qreal bottom = top + blockBoundingRect(block).height();

    while (block.isValid() && top <= e->rect().bottom()) {
        if (block.isVisible() && bottom >= e->rect().top()) {
            p.save();

            QRectF numRect( 0, top, mLineIndicator->width() - 1, bottom - top );

            int num = blockNumber;
            if (num >= selStartBlock && num <= selEndBlock) {
                num -= selStartBlock;
                p.setPen(Qt::NoPen);
                p.setBrush(plt.color(QPalette::Highlight));
                p.drawRect(numRect);
                p.setPen(plt.color(QPalette::HighlightedText));
            }

            QString number = QString::number(num + 1);
            p.drawText(0, top, mLineIndicator->width() - 4, bottom - top,
                       Qt::AlignRight, number);

            p.restore();
        }

        block = block.next();
        top = bottom;
        bottom = top + blockBoundingRect(block).height();
        ++blockNumber;
    }
    
    if(!mEditorBoxIsActive) {
        QColor color = plt.color(QPalette::Mid);
        if(color.lightness() >= 128)
            color = color.darker(60);
        else
            color = color.lighter(50);
        
        color.setAlpha(inactiveFadeAlpha());
        p.fillRect( r, color );
    }
}
开发者ID:mblewett,项目名称:supercollider,代码行数:66,代码来源:editor.cpp

示例9: paragraph

QString KTextEditingPlugin::paragraph(QTextDocument *document, int cursorPosition) const
{
    QTextBlock block = document->findBlock(cursorPosition);
    return block.text();
}
开发者ID:KDE,项目名称:koffice,代码行数:5,代码来源:KTextEditingPlugin.cpp

示例10: space

void InputField::processDocumentContentsChange(int position, int charsAdded) {
	int32 emojiPosition = 0, emojiLen = 0;
	const EmojiData *emoji = 0;

	static QString space(' ');

	QTextDocument *doc(_inner.document());
	QTextCursor c(_inner.textCursor());
	c.joinPreviousEditBlock();
	while (true) {
		int32 start = position, end = position + charsAdded;
		QTextBlock from = doc->findBlock(start), till = doc->findBlock(end);
		if (till.isValid()) till = till.next();

		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 fp = fragment.position(), fe = fp + fragment.length();
				if (fp >= end || fe <= start) {
					continue;
				}

				QString t(fragment.text());
				const QChar *ch = t.constData(), *e = ch + t.size();
				for (; ch != e; ++ch) {
					// QTextBeginningOfFrame // QTextEndOfFrame
					if (ch->unicode() == 0xfdd0 || ch->unicode() == 0xfdd1 || ch->unicode() == QChar::ParagraphSeparator || ch->unicode() == QChar::LineSeparator || ch->unicode() == '\n' || ch->unicode() == '\r') {
						if (!_inner.document()->pageSize().isNull()) {
							_inner.document()->setPageSize(QSizeF(0, 0));
						}
						int32 nlPosition = fp + (ch - t.constData());
						QTextCursor c(doc->docHandle(), nlPosition);
						c.setPosition(nlPosition + 1, QTextCursor::KeepAnchor);
						c.insertText(space);
						position = nlPosition + 1;
						emoji = TwoSymbolEmoji; // just a flag
						break;
					}
					emoji = emojiFromText(ch, e, emojiLen);
					if (emoji) {
						emojiPosition = fp + (ch - t.constData());
						break;
					}
					if (ch + 1 < e && ch->isHighSurrogate() && (ch + 1)->isLowSurrogate()) ++ch;
				}
				if (emoji) break;
			}
			if (emoji) break;
			if (b.next() != doc->end()) {
				int32 nlPosition = b.next().position() - 1;
				QTextCursor c(doc->docHandle(), nlPosition);
				c.setPosition(nlPosition + 1, QTextCursor::KeepAnchor);
				c.insertText(space);
				position = nlPosition + 1;
				emoji = TwoSymbolEmoji; // just a flag
				break;
			}
		}
		if (emoji == TwoSymbolEmoji) { // just skip
			emoji = 0;
			emojiPosition = 0;
		} else if (emoji) {
			if (!_inner.document()->pageSize().isNull()) {
				_inner.document()->setPageSize(QSizeF(0, 0));
			}

			QTextCursor c(doc->docHandle(), emojiPosition);
			c.setPosition(emojiPosition + emojiLen, QTextCursor::KeepAnchor);
			int32 removedUpto = c.position();

			insertEmoji(emoji, c);

			for (Insertions::iterator i = _insertions.begin(), e = _insertions.end(); i != e; ++i) {
				if (i->first >= removedUpto) {
					i->first -= removedUpto - emojiPosition - 1;
				} else if (i->first >= emojiPosition) {
					i->second -= removedUpto - emojiPosition;
					i->first = emojiPosition + 1;
				} else if (i->first + i->second > emojiPosition + 1) {
					i->second -= qMin(removedUpto, i->first + i->second) - emojiPosition;
				}
			}

			charsAdded -= removedUpto - position;
			position = emojiPosition + 1;

			emoji = 0;
			emojiPosition = 0;
		} else {
			break;
		}
	}
	c.endEditBlock();
}
开发者ID:noscripter,项目名称:tdesktop,代码行数:96,代码来源:flatinput.cpp

示例11: Q_UNUSED

void QSyntaxHighlighterPrivate::_q_reformatBlocks(int from, int charsRemoved, int charsAdded)
{
    Q_UNUSED(charsRemoved);
    rehighlightPending = false;

    QTextBlock block = doc->findBlock(from);
    if (!block.isValid())
        return;

    int endPosition;
    QTextBlock lastBlock = doc->findBlock(from + charsAdded);
    if (lastBlock.isValid())
        endPosition = lastBlock.position() + lastBlock.length();
    else
        endPosition = doc->docHandle()->length();

    bool forceHighlightOfNextBlock = false;

    while (block.isValid() && (block.position() < endPosition || forceHighlightOfNextBlock)) {
        const int stateBeforeHighlight = block.userState();

        reformatBlock(block);

        forceHighlightOfNextBlock = (block.userState() != stateBeforeHighlight);

        block = block.next();
    }

    formatChanges.clear();
}
开发者ID:Fale,项目名称:qtmoko,代码行数:30,代码来源:qsyntaxhighlighter.cpp

示例12: Q_ASSERT

void QTextCopyHelper::copy()
{
    if (cursor.hasComplexSelection()) {
        QTextTable *table = cursor.currentTable();
        int row_start, col_start, num_rows, num_cols;
        cursor.selectedTableCells(&row_start, &num_rows, &col_start, &num_cols);

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

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

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

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

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

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

        // add end of table
        int end = table->lastPosition();
        appendFragment(end, end+1, objectIndex);
    } else {
        appendFragments(cursor.selectionStart(), cursor.selectionEnd());
    }
}
开发者ID:muromec,项目名称:qtopia-ezx,代码行数:64,代码来源:qtextdocumentfragment.cpp

示例13: editorWidget

void CodeFoldingPanel::paintEvent(QPaintEvent *e)
{
    QTextDocument *doc = editorWidget()->document();
    TextDocumentLayout *documentLayout = qobject_cast<TextDocumentLayout*>(doc->documentLayout());
    if(!documentLayout)
        return;

    QPalette pal = areaWidget()->palette();
    pal.setCurrentColorGroup(QPalette::Active);
    QPainter painter(this);
    const QFontMetrics fm(areaWidget()->font());

    const int collapseColumnWidth = d->m_codeFoldingVisible ? foldBoxWidth(fm): 0;
    const int extraAreaWidth = d->m_extraArea->width() - collapseColumnWidth;

    painter.fillRect(e->rect(), pal.color(QPalette::Background));

    QTextBlock block = editorWidget()->firstVisibleBlock();
    int blockNumber = block.blockNumber();
    qreal top = editorWidget()->blockBoundingGeometry(block).translated(editorWidget()->contentOffset()).top();
    qreal bottom = top;

    while (block.isValid() && top <= e->rect().bottom()) {

        top = bottom;
        const qreal height = editorWidget()->blockBoundingRect(block).height();
        bottom = top + height;
        QTextBlock nextBlock = block.next();

        QTextBlock nextVisibleBlock = nextBlock;
        int nextVisibleBlockNumber = blockNumber + 1;

        if (!nextVisibleBlock.isVisible()) {
            // invisible blocks do have zero line count
            nextVisibleBlock = doc->findBlockByLineNumber(nextVisibleBlock.firstLineNumber());
            nextVisibleBlockNumber = nextVisibleBlock.blockNumber();
        }

        if (bottom < e->rect().top()) {
            block = nextVisibleBlock;
            blockNumber = nextVisibleBlockNumber;
            continue;
        }

        painter.setPen(pal.color(QPalette::Dark));

        painter.save();
        painter.setRenderHint(QPainter::Antialiasing, false);

        int extraAreaHighlightFoldBlockNumber = -1;
        int extraAreaHighlightFoldEndBlockNumber = -1;
        bool endIsVisible = false;
        if (!d->m_highlightBlocksInfo.isEmpty()) {
            extraAreaHighlightFoldBlockNumber =  d->m_highlightBlocksInfo.open.last();
            extraAreaHighlightFoldEndBlockNumber =  d->m_highlightBlocksInfo.close.first();
            endIsVisible = doc->findBlockByNumber(extraAreaHighlightFoldEndBlockNumber).isVisible();

//                    QTextBlock before = doc->findBlockByNumber(extraAreaHighlightCollapseBlockNumber-1);
//                    if (TextBlockUserData::hasCollapseAfter(before)) {
//                        extraAreaHighlightCollapseBlockNumber--;
//                    }
        }

        TextBlockUserData *nextBlockUserData = TextDocumentLayout::testUserData(nextBlock);

        bool drawBox = nextBlockUserData
                       && TextDocumentLayout::foldingIndent(block) < nextBlockUserData->foldingIndent();



        bool active = blockNumber == extraAreaHighlightFoldBlockNumber;

        bool drawStart = active;
        bool drawEnd = blockNumber == extraAreaHighlightFoldEndBlockNumber || (drawStart && !endIsVisible);
        bool hovered = blockNumber >= extraAreaHighlightFoldBlockNumber
                       && blockNumber <= extraAreaHighlightFoldEndBlockNumber;

        int boxWidth = foldBoxWidth(fm);
        if (hovered) {
            int itop = qRound(top);
            int ibottom = qRound(bottom);
            QRect box = QRect(extraAreaWidth + 1, itop, boxWidth - 2, ibottom - itop);
            drawRectBox(&painter, box, drawStart, drawEnd, pal);
        }

        if (drawBox) {
            bool expanded = nextBlock.isVisible();
            int size = boxWidth/4;
            QRect box(extraAreaWidth + size, top + size,
                      2 * (size) + 1, 2 * (size) + 1);
            d->drawFoldingMarker(&painter, pal, box, expanded, active, hovered);
        }


        painter.restore();

        block = nextVisibleBlock;
        blockNumber = nextVisibleBlockNumber;
    }
}
开发者ID:intelligide,项目名称:UnicornEdit,代码行数:100,代码来源:CodeFoldingPanel.cpp

示例14: findStartOfName

IAssistProposal *QssCompletionAssistProcessor::perform(const IAssistInterface *interface)
{
    m_interface.reset(interface);

    if (isInComment())
        return 0;

    if (interface->reason() == IdleEditor && !acceptsIdleEditor())
        return 0;

    if (m_startPosition == -1)
        m_startPosition = findStartOfName();

    QTextBlock block = interface->textDocument()->findBlock(interface->position());
    QTextBlock prevBlock = block.previous();
    Lexer lexer;
    Parser parser;
    if (prevBlock.isValid()) {
        lexer.setState(qssLexerState(prevBlock.userState()));
        parser.setState(qssParserState(prevBlock.userState()));
    }
    QList<Token> tokenList = lexer.scanMore(block.text());
    int index = m_startPosition - block.position();
    Q_FOREACH (const Token &t, tokenList) {
        if (index <= t.begin())
            break;
        parser.parseMore(t);
    }
    QStringList keywords;
    QIcon icon;
    switch (parser.state()) {
    case Parser::ObjectState:
        keywords << Lexer::objects();
        icon = QIcon(":/qsseditor/images/class.png");
        break;
    case Parser::PseudoStatesState:
        keywords << Lexer::pseudoStates();
        icon = QIcon(":/qsseditor/images/func.png");
        break;
    case Parser::SubControlState:
        keywords << Lexer::subControls();
        icon = QIcon(":/qsseditor/images/func.png");
        break;
    case Parser::AttributeNameState:
        keywords << Lexer::attributeNames();
        icon = QIcon(":/qsseditor/images/var.png");
        break;
    case Parser::AttributeBodyState:
        keywords << Lexer::attributeCtors() << Lexer::attributeKeywords();
        icon = QIcon(":/qsseditor/images/keyword.png");
        break;
    default:
        ;
    }
    keywords.removeDuplicates();
    QList<TextEditor::BasicProposalItem *> items;
    for (int i = 0; i < keywords.count(); i++) {
        BasicProposalItem *item = new QssAssistProposalItem;
        item->setText(keywords[i]);
        item->setIcon(icon);
        items.append(item);
    }
    return new GenericProposal(m_startPosition, new QssAssistProposalModel(items));
}
开发者ID:gonboy,项目名称:qsseditor,代码行数:64,代码来源:qsscompletionassist.cpp

示例15: indentForBottomLine

/*
    Returns the recommended indent for the bottom line of program.
    Unless null, typedIn stores the character of yyProgram that
    triggered reindentation.

    This function works better if typedIn is set properly; it is
    slightly more conservative if typedIn is completely wild, and
    slighly more liberal if typedIn is always null. The user might be
    annoyed by the liberal behavior.
*/
int QmlJSIndenter::indentForBottomLine(QTextBlock begin, QTextBlock end, QChar typedIn)
{
    if (begin == end)
        return 0;

    const QTextBlock last = end.previous();

    initialize(begin, last);

    QString bottomLine = last.text();
    QChar firstCh = firstNonWhiteSpace(bottomLine);
    int indent = 0;

    if (bottomLineStartsInMultilineComment()) {
        /*
            The bottom line starts in a C-style comment. Indent it
            smartly, unless the user has already played around with it,
            in which case it's better to leave her stuff alone.
        */
        if (isOnlyWhiteSpace(bottomLine))
            indent = indentWhenBottomLineStartsInMultiLineComment();
        else
            indent = indentOfLine(bottomLine);
    } else {
        if (isUnfinishedLine())
            indent = indentForContinuationLine();
        else
            indent = indentForStandaloneLine();

        if ((okay(typedIn, QLatin1Char('}')) && firstCh == QLatin1Char('}'))
            || (okay(typedIn, QLatin1Char(']')) && firstCh == QLatin1Char(']'))) {
            /*
                A closing brace is one level more to the left than the
                code it follows.
            */
            indent -= ppIndentSize;
        } else if (okay(typedIn, QLatin1Char(':'))) {
            if (caseOrDefault.exactMatch(bottomLine)) {
                /*
                    Move a case label (or the ':' in front of a
                    constructor initialization list) one level to the
                    left, but only if the user did not play around with
                    it yet. Some users have exotic tastes in the
                    matter, and most users probably are not patient
                    enough to wait for the final ':' to format their
                    code properly.

                    We don't attempt the same for goto labels, as the
                    user is probably the middle of "foo::bar". (Who
                    uses goto, anyway?)
                */
                if (indentOfLine(bottomLine) <= indent)
                    indent -= ppIndentSize;
                else
                    indent = indentOfLine(bottomLine);
            }
        }
    }

    return qMax(0, indent);
}
开发者ID:AltarBeastiful,项目名称:qt-creator,代码行数:71,代码来源:qmljsindenter.cpp


注:本文中的QTextBlock类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。