void WidgetChatInput::on_toolButtonSend_clicked()
{
	if (!textEditInput->document()->isEmpty())
	{
		if (textEditInput->document()->lineCount() > 1)
		{
			QStringList lineList = textEditInput->document()->toHtml().split("\n");
			for(int i = 4; i < lineList.size(); i++)
			{
				QTextDocument *line = new QTextDocument();
				line->setHtml(lineList.at(i));
				emit messageSent(line);
			}
		} else {
			emit messageSent(textEditInput->document());
		}
		QTextCharFormat oldFormat = textEditInput->currentCharFormat();
		textEditInput->document()->clear();
		textEditInput->setCurrentCharFormat(oldFormat);
	}
}
Example #2
1
AboutWindow::AboutWindow(QWidget *parent) :
	QDialog(parent)
{
	setWindowTitle(tr("About Symmetries"));
	setFixedSize(QSize(WINDOW_WIDTH, WINDOW_HEIGHT));

	m_appNameLabel = new QLabel(PROGRAM_NAME, this);
	QFont font = m_appNameLabel->font();
	font.setPointSize(APPNAME_FONT_POINT_SIZE);
	font.setBold(true);
	m_appNameLabel->setFont(font);

	QString appVersion("Version: ");
	appVersion.append(PROGRAM_VERSION);
	m_appVersionLabel = new QLabel(appVersion, this);

	QTextDocument* developersInfo = new QTextDocument(this);
	developersInfo->setHtml("<b>Copyright (C) 2014</b><br><br>"
		"<i>Alexey Kuzin ([email protected])</i><br>"
		"Author, Maintainer, Designer<br><br>"
		"<i>Mikhail Barenboim ([email protected])</i><br>"
		"Designer");
	m_developInfo = new QTextEdit(this);
	m_developInfo->setDocument(developersInfo);
	m_developInfo->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
	m_developInfo->setReadOnly(true);

	m_pushBtnOk = new QPushButton(tr("OK"), this);
	m_pushBtnOk->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);

	QVBoxLayout* mainLayout = new QVBoxLayout;
	mainLayout->addWidget(m_appNameLabel, 0, Qt::AlignLeft);
	mainLayout->addWidget(m_appVersionLabel, 0, Qt::AlignLeft);
	mainLayout->addWidget(m_developInfo, 1);
	mainLayout->addWidget(m_pushBtnOk, 0, Qt::AlignRight);
	setLayout(mainLayout);

	connect(m_pushBtnOk, SIGNAL(clicked()), this, SLOT(close()));
}
Example #3
0
bool MatchingText::shouldInsertNewline(const QTextCursor &tc) const
{
    QTextDocument *doc = tc.document();
    int pos = tc.selectionEnd();

    // count the number of empty lines.
    int newlines = 0;
    for (int e = doc->characterCount(); pos != e; ++pos) {
        const QChar ch = doc->characterAt(pos);

        if (! ch.isSpace())
            break;
        else if (ch == QChar::ParagraphSeparator)
            ++newlines;
    }

    if (newlines <= 1 && doc->characterAt(pos) != QLatin1Char('}'))
        return true;

    return false;
}
void
PlaylistLargeItemDelegate::drawRichText( QPainter* painter, const QRect& rect, int flags, QTextDocument& text ) const
{
    text.setPageSize( QSize( rect.width(), QWIDGETSIZE_MAX ) );
    QAbstractTextDocumentLayout* layout = text.documentLayout();

    const int height = qRound( layout->documentSize().height() );
    int y = rect.y();
    if ( flags & Qt::AlignBottom )
        y += ( rect.height() - height );
    else if ( flags & Qt::AlignVCenter )
        y += ( rect.height() - height ) / 2;

    QAbstractTextDocumentLayout::PaintContext context;
    context.palette.setColor( QPalette::Text, painter->pen().color() );

    painter->save();
    painter->translate( rect.x(), y );
    layout->draw( painter, context );
    painter->restore();
}
Example #5
0
    virtual void paintEvent( QPaintEvent *event )
    {
      bool hasAnnotations = false;
      for ( uint i = 0; i < m_document->pages(); ++i )
        if ( m_document->page( i )->hasAnnotations() ) {
          hasAnnotations = true;
          break;
        }
      if ( !hasAnnotations ) {
        QPainter p( viewport() );
        p.setRenderHint( QPainter::Antialiasing, true );
        p.setClipRect( event->rect() );

        QTextDocument document;
        document.setHtml( i18n( "<div align=center><h3>No annotations</h3>"
                                "To create new annotations press F6 or select <i>Tools -&gt; Review</i>"
                                " from the menu.</div>" ) );
        document.setTextWidth( width() - 50 );

        const uint w = document.size().width() + 20;
        const uint h = document.size().height() + 20;

        p.setBrush( palette().background() );
        p.translate( 0.5, 0.5 );
        p.drawRoundRect( 15, 15, w, h, (8*200)/w, (8*200)/h );
        p.translate( 20, 20 );
        document.drawContents( &p );

      } else {
        QTreeView::paintEvent( event );
      }
    }
Example #6
0
void ProcessItemDelegate::paint(QPainter * painter,
  const QStyleOptionViewItem &option, const QModelIndex & index) const
{
  QStyleOptionViewItemV4 opt = option;
  initStyleOption(&opt, index);

  painter->save();
  painter->setClipRect(opt.rect);

  // Draw the background.
  const QWidget * widget = opt.widget;
  QStyle * style = widget ? widget->style() : QApplication::style();
  style->proxy()->drawPrimitive(QStyle::PE_PanelItemViewItem, &opt, painter, widget);

  QRect iconRect = style->subElementRect(QStyle::SE_ItemViewItemDecoration, &opt,
    widget);
  QRect textRect = style->subElementRect(QStyle::SE_ItemViewItemText, &opt, widget);

  // Draw the icon.
  QIcon::Mode mode = QIcon::Normal;
  if (!(opt.state & QStyle::State_Enabled))
  {
    mode = QIcon::Disabled;
  }
  else if (opt.state & QStyle::State_Selected)
  {
    mode = QIcon::Selected;
  }
  QIcon::State state = opt.state & QStyle::State_Open ? QIcon::On : QIcon::Off;
  opt.icon.paint(painter, iconRect, opt.decorationAlignment, mode, state);

  // Draw the text.
  QTextDocument doc;
  doc.setHtml(opt.text);
  doc.setDocumentMargin(2);
  painter->translate(textRect.topLeft());
  doc.drawContents(painter);

  painter->restore();
}
Example #7
0
void drawHtmlLine(QPainter *painter, const QFont font, QRect rect, QString text, bool multiline,
                  bool leftAligned) {
    if(!painter){return;}

    painter->save();

    QTextDocument displayDoc;
    setUpDisplayDoc(displayDoc, font);
    if(!leftAligned){
        text = QString("<div align=\"right\">") + text + "</div>";

    }

    displayDoc.setHtml(text);
    //multiline == false - Normally
    if(multiline){
        displayDoc.setTextWidth(rect.width());
    } else {displayDoc.setTextWidth(-1);}


    painter->translate(rect.topLeft());

    if(multiline){ displayDoc.adjustSize(); }

    rect.moveTopLeft(QPoint(0,0));
    displayDoc.drawContents(painter, rect);

    painter->restore();

}
Example #8
0
void BaseEditor::findFirstOccurrance(const QString &text, QTextDocument::FindFlags qff,
                                     bool isRE, bool init, bool isSetTextCusor)
{
    if (!finded)
        return;
    QRegExp re(text);
    QTextDocument *doc = document();
    QTextCursor currentCursor = textCursor();
    QTextCursor firstCursor;
    QTextEdit::ExtraSelection es;
    if(!init || prevFindCursor.isNull())
    {
        QTextCursor startCursor;
        if(qff&QTextDocument::FindBackward && !prevFindCursor.isNull())
        {
            prevFindCursor.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor,
                      abs(prevFindCursor.selectionStart()-prevFindCursor.selectionEnd()));
        }
        if(prevFindCursor.isNull())
            startCursor = currentCursor;
        else
            startCursor = prevFindCursor;
        firstCursor = isRE ? doc->find(re, startCursor, qff):
                             doc->find(text, startCursor, qff);
    } else {
        firstCursor = isRE ? doc->find(re, prevFindCursor.selectionStart(), qff):
                             doc->find(text, prevFindCursor.selectionStart(), qff);
    }
    if(firstCursor.isNull())
    {
        QTextCursor wholeCursor(doc);
        if(qff & QTextDocument::FindBackward)
            wholeCursor.movePosition(QTextCursor::End);
        firstCursor = isRE ? doc->find(re, wholeCursor, qff):
                             doc->find(text, wholeCursor, qff);
    }
    if(firstCursor.isNull())
    {
        prevFindCursor = firstCursor;
        return;
    }
    es.cursor = firstCursor;
    QTextCharFormat f;
    f.setBackground(Qt::blue);
    f.setForeground(Qt::white);
    es.format = f;
    currentFindSelection.clear();
    currentFindSelection.append(es);
    prevFindCursor = firstCursor;
    firstCursor.clearSelection();
    if(isSetTextCusor)
        setTextCursor(firstCursor);
    ensureCursorVisible();
    updateExtraSelection();
}
Example #9
0
 void paintSection( QPainter * painter, const QRect& rect, int logicalIndex ) const override {
     
     if ( rect.isValid() ) {
         if ( logicalIndex > 0 ) {
             QStyleOptionHeader op;
             initStyleOption(&op);
             op.text = "";
             op.rect = rect;
             op.textAlignment = Qt::AlignVCenter | Qt::AlignHCenter;
             // draw the section
             style()->drawControl( QStyle::CE_Header, &op, painter, this );
             // html painting
             painter->save();
             QRect textRect = style()->subElementRect( QStyle::SE_HeaderLabel, &op, this );
             painter->translate( textRect.topLeft() );
             QTextDocument doc;
             doc.setTextWidth( textRect.width() );
             doc.setDefaultTextOption( QTextOption( Qt::AlignHCenter ) );
             doc.setDocumentMargin(0);
             doc.setHtml( model()->headerData( logicalIndex, Qt::Horizontal ).toString() );
             doc.drawContents( painter, QRect( QPoint( 0, 0 ), textRect.size() ) );
             painter->restore();
         } else {
             QHeaderView::paintSection( painter, rect, logicalIndex );
         }
     }
 }
void EventItemDelegate::paint( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
    painter->save();

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

    QVariant value = index.data();
    QBrush bgBrush = qvariant_cast<QBrush>(index.data(Qt::BackgroundRole));
    QBrush fgBrush = qvariant_cast<QBrush>(index.data(Qt::ForegroundRole));
    painter->setClipRect( opt.rect );
    painter->setBackgroundMode(Qt::OpaqueMode);
    painter->setBackground(Qt::transparent);
    painter->setBrush(bgBrush);

    if (bgBrush.style() != Qt::NoBrush) {
        QPen bgPen;
        bgPen.setColor(bgBrush.color().darker(250));
        bgPen.setStyle(Qt::SolidLine);
        bgPen.setWidth(1);
        painter->setPen(bgPen);
        painter->drawRoundedRect(opt.rect.x(), opt.rect.y(), opt.rect.width() - bgPen.width(), opt.rect.height() - bgPen.width(), 3.0, 3.0);
    }

    QTextDocument doc;
    doc.setDocumentMargin(3);
    doc.setDefaultStyleSheet("* {color: " + fgBrush.color().name() + ";}");
    doc.setHtml("<html><qt></head><meta name=\"qrichtext\" content=\"1\" />" + displayText(value, QLocale::system()) + "</qt></html>");
    QAbstractTextDocumentLayout::PaintContext context;
    doc.setPageSize( opt.rect.size());
    painter->translate(opt.rect.x(), opt.rect.y());
    doc.documentLayout()->draw(painter, context);
    painter->restore();
}
Example #11
0
QSize RichTextRenderer::findNaturalSize(int atWidth)
{
	QTextDocument doc;
	if(atWidth > 0)
		doc.setTextWidth(atWidth);
	if (Qt::mightBeRichText(html()))
		doc.setHtml(html());
	else
		doc.setPlainText(html());
	
	QSize firstSize = doc.documentLayout()->documentSize().toSize();
	QSize checkSize = firstSize;
	
// 	qDebug() << "RichTextRenderer::findNaturalSize: atWidth:"<<atWidth<<", firstSize:"<<firstSize;
	
	#define RUNAWAY_LIMIT 500
	
	int counter = 0;
	int deInc = 10;
	while(checkSize.height() == firstSize.height() &&
	      checkSize.height() > 0 &&
	      counter < RUNAWAY_LIMIT)
	{
		int w = checkSize.width() - deInc;
		doc.setTextWidth(w);
		checkSize = doc.documentLayout()->documentSize().toSize();
		
// 		qDebug() << "RichTextRenderer::findNaturalSize: w:"<<w<<", checkSize:"<<checkSize<<", counter:"<<counter;
		counter ++;
	}
	
	if(checkSize.width() != firstSize.width())
	{
		int w = checkSize.width() + deInc;
		doc.setTextWidth(w);
		checkSize = doc.documentLayout()->documentSize().toSize();
// 		qDebug() << "RichTextRenderer::findNaturalSize: Final Size: w:"<<w<<", checkSize:"<<checkSize;
		return checkSize;
	}
	else
	{
// 		qDebug() << "RichTextRenderer::findNaturalSize: No Change, firstSize:"<<checkSize;
		return firstSize;
	}
}
void SearchResultsItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem & option, const QModelIndex &index) const
{
    ResultType rType = rowItemType(index);

    if (rType == ResultTypeMatch)
    {
        QStyleOptionViewItemV4 options = option;
        initStyleOption(&options, index);

        painter->save();

        QTextDocument doc;
        doc.setHtml(options.text);

        options.text = "";
        options.widget->style()->drawControl(QStyle::CE_ItemViewItem, &options, painter);

        // shift text right to make icon visible
        QSize iconSize = options.icon.actualSize(options.rect.size());
        painter->translate(options.rect.left()+iconSize.width(), options.rect.top());
        QRect clip(0, 0, options.rect.width()+iconSize.width(), options.rect.height());

        //doc.drawContents(painter, clip);

        painter->setClipRect(clip);
        QAbstractTextDocumentLayout::PaintContext ctx;

        // set text color for selected item
        if (option.state & QStyle::State_Selected)
            ctx.palette.setColor(QPalette::Text, options.palette.highlightedText().color());

        ctx.clip = clip;
        doc.documentLayout()->draw(painter, ctx);

        painter->restore();

    } else {
        QStyledItemDelegate::paint(painter, option, index);
    }
}
Example #13
0
void QLabelPrivate::ensureTextLayouted() const
{
    if (!textLayoutDirty)
        return;
    ensureTextPopulated();
    if (control) {
        QTextDocument *doc = control->document();
        QTextOption opt = doc->defaultTextOption();

        opt.setAlignment(QFlag(this->align));

        if (this->align & Qt::TextWordWrap)
            opt.setWrapMode(QTextOption::WordWrap);
        else
            opt.setWrapMode(QTextOption::ManualWrap);

        doc->setDefaultTextOption(opt);

        QTextFrameFormat fmt = doc->rootFrame()->frameFormat();
        fmt.setMargin(0);
        doc->rootFrame()->setFrameFormat(fmt);
        doc->setTextWidth(documentRect().width());
    }
    textLayoutDirty = false;
}
Example #14
0
/*!
  Draw a text document into a rectangle

  \param painter Painter
  \param rect Traget rectangle
  \param flags Alignments/Text flags, see QPainter::drawText()
  \param text Text document
*/
void QwtPainter::drawSimpleRichText( QPainter *painter, const QRectF &rect,
    int flags, const QTextDocument &text )
{
    QTextDocument *txt = text.clone();

    painter->save();

    painter->setFont( txt->defaultFont() );
    qwtUnscaleFont( painter );

    txt->setDefaultFont( painter->font() );
    txt->setPageSize( QSizeF( rect.width(), QWIDGETSIZE_MAX ) );

    QAbstractTextDocumentLayout* layout = txt->documentLayout();

    const double height = layout->documentSize().height();
    double y = rect.y();
    if ( flags & Qt::AlignBottom )
        y += ( rect.height() - height );
    else if ( flags & Qt::AlignVCenter )
        y += ( rect.height() - height ) / 2;

    QAbstractTextDocumentLayout::PaintContext context;
    context.palette.setColor( QPalette::Text, painter->pen().color() );

    painter->translate( rect.x(), y );
    layout->draw( painter, context );

    painter->restore();
    delete txt;
}
void SoftwareColumnItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    painter->save();

    QString softwareName = index.model()->data(index.model()->index(index.row(), UpdaterDialog::Columns::SoftwareComponent)).toString();
    QString websiteURL   = index.model()->data(index.model()->index(index.row(), UpdaterDialog::Columns::WebsiteURL)).toString();

    QString link = "<img src=\":/home.png\"><a href=\"" + websiteURL + "\">"+softwareName+"</a>";

    QTextDocument document;

    if (option.state & QStyle::State_MouseOver) {
        // draw stuff which appears on mouse over
        document.setDefaultStyleSheet("a { text-decoration: none; color: darkblue; }");
    } else {
        // draw stuff that appears when mouse is not over control
        document.setDefaultStyleSheet("a { text-decoration: none; color: black; }");
    }

    document.setTextWidth(option.rect.width());
    document.setHtml(link);
    painter->translate(option.rect.topLeft());
    document.drawContents(painter);

    painter->restore();
    return;
}
Example #16
0
SimpleResourceGraph MobiExtractor::extract(const QUrl& resUri, const QUrl& fileUrl, const QString& mimeType)
{
    Q_UNUSED( mimeType );

    SimpleResource fileRes(resUri);
    SimpleResourceGraph graph;

    Mobipocket::QFileStream stream( fileUrl.toLocalFile() );
    Mobipocket::Document doc(&stream);
    if( !doc.isValid() )
        return graph;

    QMapIterator<Mobipocket::Document::MetaKey,QString> it(doc.metadata());
    while (it.hasNext()) {
        it.next();
        switch (it.key()) {
        case Mobipocket::Document::Title:
            fileRes.addProperty( NIE::title(), it.value() );
            break;
        case Mobipocket::Document::Author: {
            SimpleResource con;
            con.addType( NCO::Contact() );
            con.addProperty( NCO::fullname(), it.value() );

            fileRes.addProperty( NCO::creator(), con );
            graph << con;
            break;
        }
        case Mobipocket::Document::Description: {
            QTextDocument document;
            document.setHtml( it.value() );

            QString plain = document.toPlainText();
            if( !plain.isEmpty() )
                fileRes.addProperty( NIE::comment(), plain );
            break;
        }
        case Mobipocket::Document::Subject:
            fileRes.addProperty( NIE::subject(), it.value() );
            break;
        case Mobipocket::Document::Copyright:
            fileRes.addProperty( NIE::copyright(), it.value() );
            break;
        }
    }

    if (!doc.hasDRM()) {
        QString html = doc.text( maxPlainTextSize() );

        QTextDocument document;
        document.setHtml(html);

        QString plainText = document.toPlainText();
        if( !plainText.isEmpty() )
            fileRes.addProperty( NIE::plainTextContent(), plainText );
    }

    graph << fileRes;
    return graph;
}
Example #17
0
//-----------------------------------------------------------------------------
int ctkFittedTextBrowser::heightForWidth(int _width) const
{
  QTextDocument* doc = this->document();
  qreal savedWidth = doc->textWidth();
  
  // Fudge factor. This is the difference between the frame and the 
  // viewport.
  int fudge = 2 * this->frameWidth();
  
  // Do the calculation assuming no scrollbars
  doc->setTextWidth(_width - fudge);
  int noScrollbarHeight =
    doc->documentLayout()->documentSize().height() + fudge;
  
  // (If noScrollbarHeight is greater than the maximum height we'll be
  // allowed, then there will be scrollbars, and the actual required
  // height will be even higher. But since in this case we've already
  // hit the maximum height, it doesn't matter that we underestimate.)
  
  // Get minimum height (even if string is empty): one line of text
  int _minimumHeight = QFontMetrics(doc->defaultFont()).lineSpacing() + fudge;
  int ret = qMax(noScrollbarHeight, _minimumHeight);

  doc->setTextWidth(savedWidth);
  return ret;
}
Example #18
0
void
DelegateHelper::render_html( QPainter * painter, const QStyleOptionViewItem& option, const QString& text, const QString& css )
{
    painter->save();

    auto op = option;
    QTextDocument document;

    if ( !css.isEmpty() ) {
        document.setDefaultStyleSheet( css );
    } else {
        document.setDefaultTextOption( QTextOption( op.displayAlignment ) ); // QTBUG 13467 -- valign is not taking in account
        document.setDefaultFont( op.font );
    }
    document.setHtml( QString("<body>%1</body>").arg( text ) );

    op.displayAlignment |= Qt::AlignVCenter;
    op.text = "";
    op.widget->style()->drawControl( QStyle::CE_ItemViewItem, &op, painter );

    painter->translate( op.rect.topLeft() );
    // QRect clip( 0, 0, op.rect.width(), op.rect.height() );
    document.drawContents( painter ); //, clip );
    painter->restore();
}
Example #19
0
void EditDialog::openPrintDialog()
{
    QPrinter printer;
    QPrintPreviewDialog *dialog = new QPrintPreviewDialog(&printer);

    QTextDocument *document = new QTextDocument();
    switch (dataSource) {
    case TextBuffer:
        document->setPlainText(ui->editorText->toPlainText());
        break;
    case SciBuffer:
        // This case isn't really expected because the Scintilla widget has it's own printing slot
        document->setPlainText(sciEdit->text());
        break;
    case HexBuffer:
        document->setPlainText(hexEdit->toReadableString());
        document->setDefaultFont(hexEdit->font());
        break;
    }

    connect(dialog, &QPrintPreviewDialog::paintRequested, [&](QPrinter *previewPrinter) {
        document->print(previewPrinter);
    });

    dialog->exec();

    delete dialog;
    delete document;
}
Example #20
0
void
DelegateHelper::render_html2( QPainter * painter, const QStyleOptionViewItem& option, const QString& text )
{
    auto op = option;
    
    painter->save();

    QTextDocument document;

    document.setDefaultTextOption( QTextOption( Qt::AlignVCenter ) ); // hit to QTBUG 13467 -- valign is not taking in account ??
    document.setDefaultFont( op.font );
    document.setDefaultStyleSheet( "{ vertical-align: middle; }" );
    document.setHtml( text );

    op.displayAlignment |= Qt::AlignVCenter;
    op.text = "";
    op.widget->style()->drawControl( QStyle::CE_ItemViewItem, &op, painter, op.widget );

    QRect cbx = op.widget->style()->subElementRect( QStyle::SE_CheckBoxIndicator, &option, op.widget );
    QRect rc( option.rect );
    rc.setLeft( cbx.right() + 4 );

    painter->translate( cbx.right() + 4, option.rect.top() ); // workaround for VCenter
    document.drawContents( painter ); // rc.translated( -rc.topLeft() ) );

    painter->restore();
}
Example #21
0
    void highlightMatches(const QString &pattern)
    {
        QTextEdit *ed = qobject_cast<QTextEdit *>(m_widget);
        if (!ed)
            return;

        QTextCursor cur = ed->textCursor();

        QTextEdit::ExtraSelection selection;
        selection.format.setBackground(Qt::yellow);
        selection.format.setForeground(Qt::black);

        // Highlight matches.
        QTextDocument *doc = ed->document();
        QRegExp re(pattern);
        cur = doc->find(re);

        m_searchSelection.clear();

        int a = cur.position();
        while ( !cur.isNull() ) {
            if ( cur.hasSelection() ) {
                selection.cursor = cur;
                m_searchSelection.append(selection);
            } else {
                cur.movePosition(QTextCursor::NextCharacter);
            }
            cur = doc->find(re, cur);
            int b = cur.position();
            if (a == b) {
                cur.movePosition(QTextCursor::NextCharacter);
                cur = doc->find(re, cur);
                b = cur.position();
                if (a == b) break;
            }
            a = b;
        }

        updateExtraSelections();
    }
Example #22
0
void PlainTextEditor::indentOrUnindent( bool doIndent )
{
    QTextCursor cursor = textCursor();
    cursor.beginEditBlock();

    // Indent or unindent the selected lines
    int pos = cursor.position();
    int anchor = cursor.anchor();
    int start = qMin( anchor, pos );
    int end = qMax( anchor, pos );

    QTextDocument* doc = document();
    QTextBlock startBlock = doc->findBlock(start);
    QTextBlock endBlock = doc->findBlock( end -1 ).next();

    for ( QTextBlock block = startBlock; block != endBlock; block = block.next() ) {
        QString text = block.text();

        if ( doIndent ) {
            const int indentPosition = firstNonSpace( text );
            cursor.setPosition( block.position() +indentPosition );
            cursor.insertText( QString( IndentSize, QLatin1Char( ' ' ) ) );
        } else {
            const int indentPosition = firstNonSpace( text );
            const int targetColumn = indentedColumn( columnAt( text, indentPosition ), false );
            cursor.setPosition( block.position() +indentPosition );
            cursor.setPosition( block.position() +targetColumn, QTextCursor::KeepAnchor );
            cursor.removeSelectedText();
        }
    }

    // Reselect the selected lines
    cursor.setPosition( startBlock.position() );
    cursor.setPosition( endBlock.previous().position(), QTextCursor::KeepAnchor );
    cursor.movePosition( QTextCursor::EndOfBlock, QTextCursor::KeepAnchor );

    cursor.endEditBlock();
    setTextCursor( cursor );
}
Example #23
0
void Editor::onCurrentChanged(int idx)
{
    if(idx < 0) return;

    emit cursorPositionChanged();

    QTextDocument * document = currentTextEdit()->document();
    QTextCursor cursor = currentTextEdit()->textCursor();

    // update cursor position.
    emit cursorPositionChanged();

    // update copy/undo/redo available.
    emit copyAvailable(cursor.position() != cursor.anchor());
    emit undoAvailable(document->isUndoAvailable());
    emit redoAvailable(document->isRedoAvailable());
    emit pasteAvailable(true);

    connect(currentTextEdit(), SIGNAL(copyAvailable(bool)), this, SLOT(onCopyAvailable(bool)));
    connect(currentTextEdit(), SIGNAL(undoAvailable(bool)), this, SLOT(onUndoAvailable(bool)));
    connect(currentTextEdit(), SIGNAL(redoAvailable(bool)), this, SLOT(onRedoAvailable(bool)));
}
Example #24
0
void Html::transform(const QByteArray &input, QByteArray &output) {
    output.clear();

    if (wayValue == TransformAbstract::INBOUND) {
        for (int i = 0; i < input.size(); i++) {

            if (encodeAll) {
                output.append(encode(input.at(i)));
            } else {
                if (reserverdCharNames.contains(input.at(i))) {
                    output.append(encode(input.at(i)));
                } else {
                    output.append(input.at(i));
                }
            }
        }
    } else {
        QTextDocument text;
        text.setHtml(QString::fromUtf8(input));
        output = text.toPlainText().toUtf8();
    }
}
Example #25
0
    // We might want to optimize by passing the data to the base
    // method if the text does not contain any term matches. Would
    // need a modif to plaintorich to return the match count (easy),
    // and a way to pass an indicator from data(), a bit more
    // difficult. Anyway, the display seems fast enough as is.
    void paint(QPainter *painter, const QStyleOptionViewItem &option, 
	       const QModelIndex &index) const
    {
	QStyleOptionViewItemV4 opt = option;
	initStyleOption(&opt, index);
	QVariant value = index.data(Qt::DisplayRole);
	if (value.isValid() && !value.isNull()) {
	    QString text = value.toString();
	    if (!text.isEmpty()) {
		QTextDocument document;
		painter->save();
		if (opt.state & QStyle::State_Selected) {
		    painter->fillRect(opt.rect, opt.palette.highlight());
		    // Set the foreground color. The pen approach does
		    // not seem to work, probably it's reset by the
		    // textdocument. Couldn't use
		    // setdefaultstylesheet() either. the div thing is
		    // an ugly hack. Works for now
#if 0
		    QPen pen = painter->pen();
		    pen.setBrush(opt.palette.brush(QPalette::HighlightedText));
		    painter->setPen(pen);
#else
		    text = QString::fromUtf8("<div style='color: white'> ") + 
			text + QString::fromUtf8("</div>");
#endif
		} 
		painter->setClipRect(option.rect);
		QPoint where = option.rect.topLeft();
		where.ry() += TEXTINCELLVTRANS;
		painter->translate(where);
		document.setHtml(text);
		document.drawContents(painter);
		painter->restore();
		return;
	    } 
	}
	QStyledItemDelegate::paint(painter, option, index);
    }
QSize GrepOutputDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    const GrepOutputModel *model = dynamic_cast<const GrepOutputModel *>(index.model());
    const GrepOutputItem  *item  = dynamic_cast<const GrepOutputItem *>(model->itemFromIndex(index));

    QSize ret = QStyledItemDelegate::sizeHint(option, index);

    //take account of additional width required for highlighting (bold text)
    //and line numbers. These are not included in the default Qt size calculation.
    if(item && item->isText())
    {
        QFont font = option.font;
        font.setBold(true);
        QFontMetrics bMetrics(font);

        //TODO: calculate width with more accuracy: here the whole text is considerated as bold
        int width =  bMetrics.width(item->text()) +
                     option.fontMetrics.width(i18n("Line %1: ",item->lineNumber())) +
                     std::max(option.decorationSize.width(), 0);
        ret.setWidth(width);
    }else{
        // This is only used for titles, so not very performance critical
        QString text;
        if(item)
            text = item->text();
        else
            text = index.data().toString();
        
        QTextDocument doc;
        doc.setDocumentMargin(0);
        doc.setHtml(text);
        QSize newSize = doc.size().toSize();
        if(newSize.height() > ret.height())
            ret.setHeight(newSize.height());
    }

    ret.setHeight(ret.height()+2); // We slightly increase the vertical size, else the view looks too crowded
    return ret;
}
void MainWindow::insertCustomer(const QString &customer){
    if (customer.isEmpty())
        return;
    QStringList customerList = customer.split(", ");
    QTextDocument *document = chatbox->document();
    QTextCursor cursor = document->find("NAME");
    if (!cursor.isNull()) {
        cursor.beginEditBlock();
        cursor.insertText(customerList.at(0));
        QTextCursor oldcursor = cursor;
        cursor = document->find("ADDRESS");
        if (!cursor.isNull()) {
            for (int i = 1; i < customerList.size(); ++i) {
                cursor.insertBlock();
                cursor.insertText(customerList.at(i));
            }
            cursor.endEditBlock();
        }
        else
            oldcursor.endEditBlock();
    }
}
Example #28
0
void MainWindow::populateCache(bool ok)
{
    if (!ok || issueComboBox->count() == 1) {
        articleComboBox->setItemText(0,
                tr("- no articles available -"));
        browser->setHtml(tr("<h3><font color=red>%1</font></h3>")
                         .arg(FailMessage));
        return;
    }
    QTextDocument document;
    QMap<QString, QString> namesForUrls =
            articleLinkFetcher->namesForUrls();
    QMutableMapIterator<QString, QString> i(namesForUrls);
    while (i.hasNext()) {
        i.next();
        document.setHtml(i.value());
        i.setValue(document.toPlainText());
    }
    namesForUrlsForIssueCache[issueComboBox->currentIndex()] =
            namesForUrls;
    populateArticleComboBox();
}
Example #29
0
QString Dialog::toStringFromDocument() {
    QTextDocument *doc = message()->document();
    QString txt;
    for (QTextBlock bl = doc->begin(); bl != doc->end(); bl = bl.next())
        if (bl.isValid()) {
            for (QTextBlock::iterator it = bl.begin(); !it.atEnd(); ++it) {
                QTextFragment fragm = it.fragment();
                if (fragm.isValid() && fragm.charFormat().isImageFormat()) {
                    QString imgName = fragm.charFormat().toImageFormat().name();
                    txt += imgName;
                } else if (fragm.isValid())
                    txt += fragm.text();
            }

            if (bl != doc->begin())
                txt += "\n";
        }
    int i = (int)txt.size() - 1;
    while (i >= 0 && (txt[i] == ' ' || txt[i] == '\n')) --i;
    txt.remove(i + 1, txt.size() - i - 1);
    return txt;
}
bool db_query_widget::export_pdf()
{
  generate_html();


  QPrinter printer;
  QPrintDialog printer_dialog(&printer, NULL);
  printer_dialog.exec();
  printer.setFullPage(true);
  QTextDocument facture;
  facture.setPlainText("Test");
  facture.print(&printer);

  //QPrinter printer;
/*  pv_printer->setOrientation(QPrinter::Portrait);
  pv_printer->setPageSize(QPrinter::A4);
  pv_printer->setResolution(72);
  pv_printer->setFullPage(false);
  pv_printer->setNumCopies(1);
  pv_printer->setOutputFileName("test.pdf");
  pv_printer->setOutputFormat(QPrinter::PdfFormat);
*/

  //QPrintDialog printer_dialog(&printer, this);
    //pv_text_doc->setHtml("hello");
    //pv_text_doc->setHtml("<table width=\"100%\" border=\"1\" cellspacing=0>\nhello\n</table>\n");
    //te_text->setDocument(pv_text_doc);
  //if(printer_dialog.exec()){
    //QPainter painter(&printer);

  //pv_painter->begin(pv_printer);

    pv_text_doc->setHtml(pv_html);
    //pv_text_doc->print(pv_printer);

    //pv_painter->end();
  //}
  return false; // nothing's working here...
}