void ChatView::doTrackBar() { // save position, because our manipulations could change it int scrollbarValue = verticalScrollBar()->value(); QTextCursor cursor = textCursor(); cursor.beginEditBlock(); PsiRichText::Selection selection = PsiRichText::saveSelection(this, cursor); //removeTrackBar(cursor); if (oldTrackBarPosition) { cursor.setPosition(oldTrackBarPosition, QTextCursor::KeepAnchor); QTextBlockFormat blockFormat = cursor.blockFormat(); blockFormat.clearProperty(QTextFormat::BlockTrailingHorizontalRulerWidth); cursor.clearSelection(); cursor.setBlockFormat(blockFormat); } //addTrackBar(cursor); cursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor); oldTrackBarPosition = cursor.position(); QTextBlockFormat blockFormat = cursor.blockFormat(); blockFormat.setProperty(QTextFormat::BlockTrailingHorizontalRulerWidth, QVariant(true)); cursor.clearSelection(); cursor.setBlockFormat(blockFormat); PsiRichText::restoreSelection(this, cursor, selection); cursor.endEditBlock(); setTextCursor(cursor); verticalScrollBar()->setValue(scrollbarValue); }
void KNoteEdit::textList() { QTextCursor c = textCursor(); c.beginEditBlock(); if ( m_textList->isChecked() ) { QTextListFormat lf; QTextBlockFormat bf = c.blockFormat(); lf.setIndent( bf.indent() + 1 ); bf.setIndent( 0 ); lf.setStyle( QTextListFormat::ListDisc ); c.setBlockFormat( bf ); c.createList( lf ); } else { QTextBlockFormat bf; bf.setObjectIndex( -1 ); c.setBlockFormat( bf ); } c.endEditBlock(); }
void GraphicTextDialog::textStyle(int styleIndex) { QTextCursor cursor = textEdit->textCursor(); if(styleIndex != 0) { QTextListFormat::Style style = QTextListFormat::ListDisc; switch (styleIndex) { default: case 1: style = QTextListFormat::ListDisc; break; case 2: style = QTextListFormat::ListCircle; break; case 3: style = QTextListFormat::ListSquare; break; case 4: style = QTextListFormat::ListDecimal; break; case 5: style = QTextListFormat::ListLowerAlpha; break; case 6: style = QTextListFormat::ListUpperAlpha; break; } cursor.beginEditBlock(); QTextBlockFormat blockFmt = cursor.blockFormat(); QTextListFormat listFmt; if(cursor.currentList()) { listFmt = cursor.currentList()->format(); } else { listFmt.setIndent(blockFmt.indent() + 1); blockFmt.setIndent(0); cursor.setBlockFormat(blockFmt); } listFmt.setStyle(style); cursor.createList(listFmt); cursor.endEditBlock(); } else { // #### QTextBlockFormat bfmt; bfmt.setObjectIndex(-1); cursor.mergeBlockFormat(bfmt); } }
void GpxBlock::updateTextPosition() { QPointF pos; //_name_item.setTextWidth(_name_item.boundingRect().width()); QTextCursor cursor = _name_item.textCursor(); QTextBlockFormat bfmt = cursor.blockFormat(); bfmt.setAlignment(Qt::AlignCenter); cursor.setBlockFormat(bfmt); _name_item.setTextCursor(cursor); _name_item.setTextWidth(_width+20); switch (direction()) { case Graphic::RIGHT: pos.setX(-(_name_item.boundingRect().width()/2)); pos.setY(_height / 2 + 3); break; case Graphic::LEFT: pos.setX((_name_item.boundingRect().width() / 2)); pos.setY(-_height / 2 - 3); break; case Graphic::DOWN: pos.setY((_name_item.boundingRect().width() / 2)); pos.setX(_width/ 2 + 3); break; case Graphic::UP: pos.setY(-(_name_item.boundingRect().width() / 2)); pos.setX(-_width / 2 - 3); break; } _name_item.setPos(pos); }
void MRichTextEdit::list(bool checked, QTextListFormat::Style style) { QTextCursor cursor = f_textedit->textCursor(); cursor.beginEditBlock(); if (!checked) { QTextBlockFormat obfmt = cursor.blockFormat(); QTextBlockFormat bfmt; bfmt.setIndent(obfmt.indent()); cursor.setBlockFormat(bfmt); } else { QTextListFormat listFmt; if (cursor.currentList()) { listFmt = cursor.currentList()->format(); } listFmt.setStyle(style); cursor.createList(listFmt); } cursor.endEditBlock(); }
//段落标号、编号 void MyChild::setStyle(int style) { QTextCursor cursor = this->textCursor(); if (style != 0) { QTextListFormat::Style stylename = QTextListFormat::ListDisc; switch (style) { default: case 1: stylename = QTextListFormat::ListDisc; break; case 2: stylename = QTextListFormat::ListCircle; break; case 3: stylename = QTextListFormat::ListSquare; break; case 4: stylename = QTextListFormat::ListDecimal; break; case 5: stylename = QTextListFormat::ListLowerAlpha; break; case 6: stylename = QTextListFormat::ListUpperAlpha; break; case 7: stylename = QTextListFormat::ListLowerRoman; break; case 8: stylename = QTextListFormat::ListUpperRoman; break; } cursor.beginEditBlock(); QTextBlockFormat blockFmt = cursor.blockFormat(); QTextListFormat listFmt; if (cursor.currentList()) { listFmt = cursor.currentList()->format(); } else { listFmt.setIndent(blockFmt.indent() + 1); blockFmt.setIndent(0); cursor.setBlockFormat(blockFmt); } listFmt.setStyle(stylename); cursor.createList(listFmt); cursor.endEditBlock(); } else { QTextBlockFormat bfmt; bfmt.setObjectIndex(-1); cursor.mergeBlockFormat(bfmt); } }
WndListenJob::WndListenJob( int i_job_id, const QString & i_name): WndText( "Listen Job"), m_job_id( i_job_id), m_name( i_name) { #if QT_VERSION >= 0x040300 layout->setContentsMargins( 10, 10, 10, 10); #endif setContentsMargins(1,1,1,1); qTextEdit->moveCursor( QTextCursor::End, QTextCursor::KeepAnchor); QTextCursor cursor = qTextEdit->textCursor(); QTextBlockFormat blockFormat; // blockFormat.setTopMargin(-5); // blockFormat.setBottomMargin(-5); cursor.setBlockFormat( blockFormat); qTextEdit->setTextCursor( cursor); qTextEdit->setWordWrapMode( QTextOption::NoWrap); m_name = QString("Listening \"%1\"").arg( m_name); setWindowTitle( m_name); subscribe( true); }
void NoteEditWidget::resizeEvent(QResizeEvent *) { int screenWidth = width(); int screenHeight = height(); if (screenWidth > screenHeight) { // we have a classical landscape monitor noteEditHeight = screenHeight - TextEditMargin; noteEditWidth = static_cast<int>(noteEditHeight * NoteEditWidthMultiplier); } else { // we have monitor standing in portrait noteEditWidth = screenWidth - TextEditMargin; noteEditHeight = static_cast<int>(noteEditWidth / NoteEditWidthMultiplier); } noteEditXPos = (screenWidth - noteEditWidth) / 2; noteEditYPos = (screenHeight - noteEditHeight) / 2; visualCover->setGeometry(0, 0, width(), height()); textEdit->setGeometry(noteEditXPos, noteEditYPos, noteEditWidth, noteEditHeight); textEdit->setFocus(); textEdit->setFont(getFontForTextEditWith(noteEditWidth)); for (QTextBlock block = textEdit->document()->begin(); block.isValid(); block = block.next()) { QTextCursor tc = QTextCursor(block); QTextBlockFormat fmt = block.blockFormat(); fmt.setLineHeight(LineHeightPercentage, QTextBlockFormat::ProportionalHeight); tc.setBlockFormat(fmt); } }
void MainWindow::highlightListItems() { QTextCursor cursor = editor->textCursor(); QTextList *list = cursor.currentList(); if (!list) return; cursor.beginEditBlock(); //! [0] for (int index = 0; index < list->count(); ++index) { QTextBlock listItem = list->item(index); //! [0] QTextBlockFormat newBlockFormat = listItem.blockFormat(); newBlockFormat.setBackground(Qt::lightGray); QTextCursor itemCursor = cursor; itemCursor.setPosition(listItem.position()); //itemCursor.movePosition(QTextCursor::StartOfBlock); itemCursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); itemCursor.setBlockFormat(newBlockFormat); /* //! [1] processListItem(listItem); //! [1] */ //! [2] } //! [2] cursor.endEditBlock(); }
void MainWindow::increaseIndent() { QTextBlockFormat blockFmt = ui->textNote->textCursor().blockFormat(); QTextCursor cursor = ui->textNote->textCursor(); blockFmt.setIndent(blockFmt.indent()+1); cursor.setBlockFormat(blockFmt); }
void Stack::setBlockHeading(int heading) { m_current_document->setRichText(true); QTextCursor cursor = m_current_document->text()->textCursor(); QTextBlockFormat block_format = cursor.blockFormat(); block_format.setProperty(QTextFormat::UserProperty, heading); cursor.setBlockFormat(block_format); }
void Stack::increaseIndent() { m_current_document->setRichText(true); QTextCursor cursor = m_current_document->text()->textCursor(); QTextBlockFormat format = cursor.blockFormat(); format.setIndent(format.indent() + 1); cursor.setBlockFormat(format); emit updateFormatActions(); }
void FormText::alignRight() { QTextCursor c = textCursor(); QTextBlockFormat b = c.blockFormat(); b.setAlignment( Qt::AlignRight ); c.setBlockFormat( b ); setTextCursor( c ); }
void FillCellHelper::fill( QTextTable* textTable, KDReports::ReportBuilder& builder, QTextDocument& textDoc, QTextTableCell& cell ) { cellCursor = cell.firstCursorPosition(); QTextCharFormat cellFormat = cell.format(); if ( background.isValid() ) { cellFormat.setBackground( background ); } cellFormat.setVerticalAlignment( toVerticalAlignment( alignment ) ); cell.setFormat( cellFormat ); QTextBlockFormat blockFormat = cellCursor.blockFormat(); blockFormat.setAlignment( alignment ); blockFormat.setNonBreakableLines( nonBreakableLines ); builder.setupBlockFormat( blockFormat ); cellCursor.setBlockFormat( blockFormat ); const bool hasIcon = !cellDecoration.isNull(); const bool iconAfterText = decorationAlignment.isValid() && ( decorationAlignment.toInt() & Qt::AlignRight ); if ( hasIcon && !iconAfterText ) { insertDecoration( builder, textDoc ); } QTextCharFormat charFormat = cellCursor.charFormat(); if ( cellFont.isValid() ) { QFont cellQFont = qvariant_cast<QFont>( cellFont ); #if QT_VERSION >= QT_VERSION_CHECK(5, 3, 0) charFormat.setFont( cellQFont, QTextCharFormat::FontPropertiesSpecifiedOnly ); #else charFormat.setFont( cellQFont ); #endif } else { charFormat.setFont( builder.defaultFont() ); } if ( foreground.isValid() ) charFormat.setForeground( foreground ); cellCursor.setCharFormat( charFormat ); if ( hasIcon && !iconAfterText ) { cellCursor.insertText( QChar::fromLatin1( ' ' ) ); // spacing between icon and text } //qDebug() << cellText; if (cellText.startsWith(QLatin1String("<qt>")) || cellText.startsWith(QLatin1String("<html>"))) cellCursor.insertHtml( cellText ); else cellCursor.insertText( cellText ); if ( hasIcon && iconAfterText ) { cellCursor.insertText( QChar::fromLatin1( ' ' ) ); // spacing between icon and text insertDecoration( builder, textDoc ); } if ( span.width() > 1 || span.height() > 1 ) textTable->mergeCells( cell.row(), cell.column(), span.height(), span.width() ); }
void NotesWindow::setVisible(bool visible) { if (ui->textEdit->document()->isEmpty()) { qSort(m_notes); QTextCursor cursor = ui->textEdit->textCursor(); foreach (const NoteText ¬e, m_notes) { //cursor.insertText(s_separator); cursor.insertHtml(QStringLiteral("<hr>")); cursor.insertBlock(); cursor.setBlockFormat(QTextBlockFormat()); cursor.insertHtml(note.htmlHeader()); cursor.setBlockFormat(QTextBlockFormat()); cursor.insertBlock(); cursor.insertBlock(); if (note.isHtml()) cursor.insertHtml(note.text()); else cursor.insertText(note.text()); }
void MainWindow::decreaseIndent() { QTextBlockFormat blockFmt = ui->textNote->textCursor().blockFormat(); QTextCursor cursor = ui->textNote->textCursor(); if(blockFmt.indent() > 0) blockFmt.setIndent(blockFmt.indent()-1); else blockFmt.setIndent(0); cursor.setBlockFormat(blockFmt); }
void MainWindow::toggleList(QTextListFormat::Style style) { QTextCursor cursor = ui->textNote->textCursor(); QTextBlockFormat blockFmt = cursor.blockFormat(); QTextListFormat listFmt; bool list = (cursor.currentList() != 0); // change style if list exists and is a different style if(list && cursor.currentList()->format().style() != style) { listFmt.setStyle(style); cursor.currentList()->setFormat(listFmt); } // remove list if exists and matches style else if(list&& cursor.currentList()->format().style() == style) { cursor.currentList()->removeItem(0); blockFmt = ui->textNote->textCursor().blockFormat(); cursor = ui->textNote->textCursor(); blockFmt.setIndent(0); cursor.setBlockFormat(blockFmt); // create list if not exists } else { cursor.beginEditBlock(); if (cursor.currentList()) { listFmt = cursor.currentList()->format(); } else { listFmt.setIndent(blockFmt.indent() + 1); blockFmt.setIndent(0); cursor.setBlockFormat(blockFmt); } listFmt.setStyle(style); cursor.createList(listFmt); cursor.endEditBlock(); } updateMenus(); }
void TextEditor::toggleRightAlign(bool val) { QTextCursor cursor = edit->textCursor(); QTextBlockFormat f = cursor.blockFormat(); f.setAlignment(val ? Qt::AlignRight : Qt::AlignLeft); cursor.setBlockFormat(f); edit->setTextCursor(cursor); if (val) { leftAlign->setChecked(false); centerAlign->setChecked(false); // rightAlign->setChecked(false); } }
void ChatMessageArea::setHtml(const QString& html) { // Create format with updated line height QTextBlockFormat format; format.setLineHeight(CHAT_MESSAGE_LINE_HEIGHT, QTextBlockFormat::ProportionalHeight); // Possibly a bug in QT, the format won't take effect if `insertHtml` is used first. Inserting a space and deleting // it after ensures the format is applied. QTextCursor cursor = textCursor(); cursor.setBlockFormat(format); cursor.insertText(" "); cursor.insertHtml(html); cursor.setPosition(0); cursor.deleteChar(); }
/*! * \brief Changes the list attribute of the selected text to \a v */ void QwwRichTextEdit::setList(bool v){ QTextCursor cur = textCursor(); if(v){ QTextListFormat listFormat; listFormat.setStyle(QTextListFormat::ListDisc); currentList = cur.createList(listFormat); } else { cur.setBlockFormat(QTextBlockFormat()); // cur.movePosition(QTextCursor::NextBlock); // cur.insertBlock(QTextBlockFormat()); setTextCursor(cur); currentList = 0; } }
void XYZTextEditor::textDirection() { QTextCursor cursor = m_ui->textEdit->textCursor(); QTextBlockFormat blockFmt = cursor.blockFormat(); QTextOption topt = m_ui->textEdit->document()->defaultTextOption(); if (m_ui->btnTextDirection->isChecked()) { topt.setTextDirection(Qt::RightToLeft); blockFmt.setLayoutDirection(Qt::RightToLeft); } else { topt.setTextDirection(Qt::LeftToRight); blockFmt.setLayoutDirection(Qt::LeftToRight); } m_ui->textEdit->document()->setDefaultTextOption(topt); cursor.setBlockFormat(blockFmt); }
void MRichTextEdit::indent(int delta) { QTextCursor cursor = f_textedit->textCursor(); cursor.beginEditBlock(); QTextBlockFormat bfmt = cursor.blockFormat(); int ind = bfmt.indent(); if (ind + delta >= 0) { bfmt.setIndent(ind + delta); } cursor.setBlockFormat(bfmt); cursor.endEditBlock(); }
void ConsoleLog::appendToLog(QString message) { bool scrollToBottom = false; if(_log->verticalScrollBar()->value() == _log->verticalScrollBar()->maximum()) { scrollToBottom = true; } QTextBlockFormat format; format.setLineHeight(30, 0); QTextCursor cursor = _log->textCursor(); cursor.setBlockFormat(format); int pos = cursor.position(); cursor.setPosition(_log->toPlainText().length()); cursor.insertHtml(message + "<br/><br/><br/>"); cursor.setPosition(pos); if(scrollToBottom) _log->verticalScrollBar()->setValue(_log->verticalScrollBar()->maximum()); }
WndListenJob::WndListenJob( int JobId, const QString & Name): WndText( "Listen Job"), jobid( JobId), jobname( Name) { #if QT_VERSION >= 0x040300 layout->setContentsMargins( 10, 10, 10, 10); #endif setContentsMargins(1,1,1,1); qTextEdit->moveCursor( QTextCursor::End, QTextCursor::KeepAnchor); QTextCursor cursor = qTextEdit->textCursor(); QTextBlockFormat blockFormat; blockFormat.setTopMargin(-5); blockFormat.setBottomMargin(-5); cursor.setBlockFormat( blockFormat); qTextEdit->setTextCursor( cursor); qTextEdit->setWordWrapMode( QTextOption::NoWrap); setWindowTitle( jobname); af::MCListenAddress mclass( af::MCListenAddress::TOLISTEN, Watch::getClientAddress(), jobid); Watch::sendMsg( new af::Msg( af::Msg::TTaskListenOutput, &mclass)); }
void TextEditWidget::sl_ListButton_Toggled(bool toggle) { QTextCursor cursor = this->textField->textCursor(); if (toggle) { if (cursor.currentList()) { WARNING("Wrong button state"); return; } QTextListFormat format; format.setStyle(QTextListFormat::ListDisc); cursor.createList(format); } else { QTextList *textList = cursor.currentList(); if (!cursor.currentList()) { WARNING("Wrong button state"); return; } QTextBlock block = cursor.block(); textList->remove(block); QTextBlockFormat format = block.blockFormat(); format.setIndent(0); cursor.setBlockFormat(format); } }
//Lecture des paragraphes bool OpenDocument::contenu_paragraphe(QDomElement e, QTextCursor &curseur, bool puces, bool h_item, bool tableau){ ErrorManager instance_erreur; p_current++; case_tableau = ""; //On change la QProgressBar //chargement-> QString nom_style = e.attribute("text:style-name", "default"); QTextCharFormat format = cree_bloc_format(nom_style); //On récupère le format de bloc QTextBlockFormat format_bloc = cree_bloc_format2(nom_style); //On ajoute un marginTop de 5 pour plus de lisibilité format_bloc.setTopMargin(2); //Style spécifique aux puces if(puces || h_item){ int id_style = -1; for(int i=0; i<styles.size(); i++){ //On parcourt les styles if(id_style >= 0){ break; } for(int j=0; j<styles.at(i).size(); j++){ //On rentre dans le QMultiMap if(puces){ if(styles.at(i).value("style-puces") == nom_style){ id_style = i; //On sort de la boucle break; } } else{ //Ce ne peut être que le "h_item" sinon la boucle ne se déclencherait pas if(styles.at(i).value("style-h") == nom_style){ id_style = i; //On se casse break; } } } } if(id_style != -1){ //On merge le style format.merge(cree_bloc_format(styles.at(id_style).value("style-puces"))); } } //On applique le format au curseur curseur.setCharFormat(format); if(!tableau){ curseur.beginEditBlock(); } curseur.setBlockCharFormat(format); curseur.setBlockFormat(format_bloc); if(puces){ contenu_puce.append("<li>"); //On vérifie la taille int taille = format.fontPointSize(); if(taille == 0){ //Il y a eu un bug lors de la sélection du style, on applique la taille par défaut format.setFontPointSize(12); } } //Maintenant on lit les <span> QDomNode enfants = e.firstChild(); while(!enfants.isNull()){ if(enfants.isElement()){ QDomElement type = enfants.toElement(); //On parcours le type d'élément if(type.tagName() == "text:span"){ traite_span(format, curseur, type, puces, tableau); } else if(type.tagName() == "text:a"){ //Il s'agit d'un lien traite_lien(curseur, type, format); } else if(type.tagName() == "text:line-break"){ } else if(type.tagName() == "text:s"){ curseur.insertText(QString(" ")); } else if(type.tagName() == "text:tab"){ curseur.insertText(QString(" ")); } else if(type.tagName() == "draw:frame"){ QDomNode enfants_image = type.firstChild(); QString style_image = type.attribute("draw:style-name"); if(enfants_image.toElement().tagName() == "draw:image"){ if(!traite_image(curseur, enfants_image.toElement(), style_image)){ instance_erreur.Erreur_msg(tr("ODT : Erreur lors de la lecture des images (return false)"), QMessageBox::Ignore); } } } else if(type.tagName() == "text:list"){ if(!contenu_puces(type, curseur)){ instance_erreur.Erreur_msg(tr("ODT : Une erreur est survenue lors de la lecture d'une liste à puces; elle ne sera pas affichée"), QMessageBox::Warning); } else{ QTextCursor curseur(document); curseur.movePosition(QTextCursor::End); curseur.movePosition(QTextCursor::PreviousBlock); curseur.insertHtml(contenu_puce); contenu_puce = ""; } } else if(type.tagName() == "text:soft-page-break"){ } else{ instance_erreur.Erreur_msg(tr("ODT: Type de contenu non supporté : %1").arg(type.tagName()), QMessageBox::Ignore); } } else if(enfants.isText()){ //On gére le texte if(!puces && !tableau){ curseur.insertText(enfants.nodeValue(), format); } else if(tableau){ case_tableau.append(enfants.nodeValue()); } else{ //Insertion du contenu des puces si on est dans un "p" //On récupère le style par défaut QTextDocument *temp = new QTextDocument; QTextCursor curseur(temp); curseur.insertText(enfants.nodeValue(), format); contenu_puce.append(nettoye_code(temp->toHtml())); delete temp; } } else{ instance_erreur.Erreur_msg(tr("ODT : type de données non supporté"), QMessageBox::Ignore); } enfants = enfants.nextSibling(); } //On a fini la boucle OU il n'y avait pas de <span> //On récupère le contenu if(!puces && !tableau){ curseur.insertText("\n"); } if(puces){ contenu_puce.append("</li>"); } if(!tableau){ curseur.endEditBlock(); } if(tableau){ ligne_tableau.append(case_tableau); } //std::cout << e.text().toStdString() << std::endl; return true; }
void QGithubMarkdown::read(const QByteArray &markdown, QTextDocument *target) { doc = target; doc->clear(); cursor = QTextCursor(doc); cursor.beginEditBlock(); const QList<Token> tokens = tokenize(clean(QString::fromUtf8(markdown))); const QList<Paragraph> paragraphs = paragraphize(tokens); const auto paralists = listize(paragraphs); //std::for_each(paragraphs.begin(), paragraphs.end(), [](const Paragraph &item){qDebug() << item;}); bool firstBlock = true; for (const auto paralist : paralists) { auto insertTokens = [&](const QList<Token> &tokens, const QTextCharFormat &format, const bool isCode) { QTextCharFormat fmt(format); QTextCharFormat codeFmt(format); codeFmt.setFontFamily("Monospace"); QListIterator<Token> iterator(tokens); while (iterator.hasNext()) { const Token token = iterator.next(); if (isCode) { cursor.insertText(token.source); } else { if (token.type == Token::Bold) { if (fmt.fontWeight() == QFont::Bold) { fmt.setFontWeight(QFont::Normal); } else { fmt.setFontWeight(QFont::Bold); } } else if (token.type == Token::Italic) { fmt.setFontItalic(!fmt.fontItalic()); } else if (token.type == Token::InlineCodeDelimiter) { while (iterator.hasNext()) { const Token next = iterator.next(); if (next.type == Token::InlineCodeDelimiter) { break; } else { cursor.insertText(token.source, codeFmt); } } } else if (token.type == Token::Character) { cursor.insertText(token.content.toChar(), fmt); } else { cursor.insertText(token.source, fmt); } } } }; if (paralist.second.indent == -1) { const Paragraph paragraph = paralist.first; QTextCharFormat charFmt; QTextBlockFormat blockFmt; blockFmt.setBottomMargin(5.0f); if (Paragraph::FirstHeading <= paragraph.type && paragraph.type <= Paragraph::LastHeading) { charFmt.setFontPointSize(sizeMap[paragraph.type]); } else if (paragraph.type == Paragraph::Quote) { blockFmt.setIndent(1); } else if (paragraph.type == Paragraph::Code) { blockFmt.setNonBreakableLines(true); charFmt.setFontFamily("Monospace"); } if (!firstBlock) { cursor.insertBlock(); } else { firstBlock = false; } cursor.setBlockFormat(blockFmt); cursor.block().setUserState(paragraph.type); insertTokens(paragraph.tokens, charFmt, paragraph.type == Paragraph::Code); } else { const List list = paralist.second; qDebug() << "##########################" << list.indent << list.ordered; std::for_each(list.paragraphs.begin(), list.paragraphs.end(), [](const Paragraph &item){qDebug() << item;}); cursor.setBlockFormat(QTextBlockFormat()); cursor.setBlockCharFormat(QTextCharFormat()); QTextListFormat listFormat; listFormat.setStyle(list.ordered ? QTextListFormat::ListDecimal : QTextListFormat::ListDisc); listFormat.setIndent(list.indent); QTextList *l = cursor.insertList(listFormat); qDebug() << "inserting list" << list.indent; bool firstBlock = true; for (const Paragraph ¶graph : list.paragraphs) { if (firstBlock) { firstBlock = false; } else { cursor.insertBlock(); qDebug() << "inserting block"; } insertTokens(paragraph.tokens, QTextCharFormat(), false); qDebug() << l->count(); l->add(cursor.block()); qDebug() << l->count(); qDebug() << "inserting characters"; } } } cursor.endEditBlock(); qDebug() << doc->toHtml(); }
bool OpenDocument::traite_image(QTextCursor &curseur, QDomElement e, QString nom){ ErrorManager instance_erreur; QString file = ""; if(e.tagName() != "draw:image"){ instance_erreur.Erreur_msg(tr("ODT : Mauvais paramètre envoyé : fonction de lecture d'image"), QMessageBox::Ignore); return false; } //On détecte si elle est en local ou en HTTP if(e.attribute("xlink:href").contains("http")){//Internet //On va piocher l'image sur Internet //On nettoye l'URL QString url_temp = e.attribute("xlink:href"); if(url_temp.indexOf("?", 0) > 0){ //Il y en a -> on vire tout ce qui est après int pos_depart = url_temp.indexOf("?", 0); int fin = url_temp.size(); url_temp = url_temp.remove(pos_depart, fin); } QUrl url_image(url_temp); if(!url_image.isValid()){ instance_erreur.Erreur_msg(tr("ODT : Erreur lors du téléchargement d'éléments distants"), QMessageBox::Ignore); return false; } QNetworkAccessManager nw_manager; QNetworkRequest request(url_image); QNetworkReply *reponse = nw_manager.get(request); QEventLoop eventLoop; QObject::connect(reponse, SIGNAL(finished()), &eventLoop, SLOT(quit())); eventLoop.exec(); QImage image; image.loadFromData(reponse->readAll()); QString ext = url_image.toString(); ext = ext.remove(0, (ext.size()-4)); qsrand(QDateTime::currentDateTime ().toTime_t ()); file = QDir::tempPath()+QDir::separator()+QString::number(qrand())+".png"; if(!image.isNull()){ if(!image.save(file, "PNG")){ //!sauvegarde instance_erreur.Erreur_msg(tr("ODT : Sauvegarde échouée de l'image téléchargée"), QMessageBox::Ignore); return false; } } else{ //Image nulle instance_erreur.Erreur_msg(tr("ODT : Téléchargement échoué d'une image"), QMessageBox::Ignore); return false; } delete reponse; } else if(e.attribute("xlink:href").contains("Pictures")){//Local //On extrait le fichier QZipReader image(nom_odt, QIODevice::ReadOnly); Outils instance_outils; QString clean_fichier = e.attribute("xlink:href"); clean_fichier = clean_fichier.split("/").last(); image.extractOne(QDir::tempPath(), clean_fichier); image.close(); //On sélectionne le fichier file = QDir::tempPath()+QDir::separator()+clean_fichier; } else{ //C'est pas normal ça : on se casse instance_erreur.Erreur_msg(tr("ODT : source d'image non trouvée"), QMessageBox::Ignore); return false; } //On affiche l'image QTextImageFormat format_image; format_image = cree_image_format(nom); format_image.setName(file); //On récupère d'éventuelles spécifications de taille QDomNode enfants = e.parentNode(); e = enfants.toElement(); //Width de l'image if(e.hasAttribute("svg:width")){ QString width = e.attribute("svg:width"); double value = width.left(width.length() - 2).toDouble(); format_image.setWidth(value*28.3465058); } //Height de l'image if(e.hasAttribute("svg:height")){ QString height = e.attribute("svg:height"); double value = height.left(height.length() - 2).toDouble(); format_image.setHeight(value*28.34650058); } QTextBlockFormat format_block_image; format_block_image = cree_bloc_format2(nom); curseur.insertBlock(); curseur.movePosition(QTextCursor::PreviousBlock); curseur.setBlockFormat(format_block_image); curseur.insertImage(format_image); curseur.movePosition(QTextCursor::End); return true; }
void CDiaryEdit::draw(QTextDocument& doc) { CDiaryEditLock lock(this); QFontMetrics fm(QFont(font().family(),10)); bool hasGeoCaches = false; int cnt; int w = doc.textWidth(); int pointSize = ((10 * (w - 2 * ROOT_FRAME_MARGIN)) / (CHAR_PER_LINE * fm.width("X"))); if(pointSize == 0) return; doc.setUndoRedoEnabled(false); QFont f = textEdit->font(); f.setPointSize(pointSize); textEdit->setFont(f); QTextCharFormat fmtCharHeading1; fmtCharHeading1.setFont(f); fmtCharHeading1.setFontWeight(QFont::Black); fmtCharHeading1.setFontPointSize(f.pointSize() + 8); QTextCharFormat fmtCharHeading2; fmtCharHeading2.setFont(f); fmtCharHeading2.setFontWeight(QFont::Black); fmtCharHeading2.setFontPointSize(f.pointSize() + 4); QTextCharFormat fmtCharStandard; fmtCharStandard.setFont(f); QTextCharFormat fmtCharHeader; fmtCharHeader.setFont(f); fmtCharHeader.setBackground(Qt::darkBlue); fmtCharHeader.setFontWeight(QFont::Bold); fmtCharHeader.setForeground(Qt::white); QTextBlockFormat fmtBlockStandard; fmtBlockStandard.setTopMargin(10); fmtBlockStandard.setBottomMargin(10); fmtBlockStandard.setAlignment(Qt::AlignJustify); QTextFrameFormat fmtFrameStandard; fmtFrameStandard.setTopMargin(5); fmtFrameStandard.setBottomMargin(5); fmtFrameStandard.setWidth(w - 2 * ROOT_FRAME_MARGIN); QTextFrameFormat fmtFrameRoot; fmtFrameRoot.setTopMargin(ROOT_FRAME_MARGIN); fmtFrameRoot.setBottomMargin(ROOT_FRAME_MARGIN); fmtFrameRoot.setLeftMargin(ROOT_FRAME_MARGIN); fmtFrameRoot.setRightMargin(ROOT_FRAME_MARGIN); QTextTableFormat fmtTableStandard; fmtTableStandard.setBorder(1); fmtTableStandard.setBorderBrush(Qt::black); fmtTableStandard.setCellPadding(4); fmtTableStandard.setCellSpacing(0); fmtTableStandard.setHeaderRowCount(1); fmtTableStandard.setTopMargin(10); fmtTableStandard.setBottomMargin(20); fmtTableStandard.setWidth(w - 2 * ROOT_FRAME_MARGIN); QVector<QTextLength> constraints; constraints << QTextLength(QTextLength::FixedLength, 32); constraints << QTextLength(QTextLength::VariableLength, 50); constraints << QTextLength(QTextLength::VariableLength, 100); fmtTableStandard.setColumnWidthConstraints(constraints); doc.rootFrame()->setFrameFormat(fmtFrameRoot); QTextCursor cursor = doc.rootFrame()->firstCursorPosition(); cursor.insertText(diary.getName(), fmtCharHeading1); cursor.setCharFormat(fmtCharStandard); cursor.setBlockFormat(fmtBlockStandard); diary.diaryFrame = cursor.insertFrame(fmtFrameStandard); { QTextCursor cursor1(diary.diaryFrame); cursor1.setCharFormat(fmtCharStandard); cursor1.setBlockFormat(fmtBlockStandard); if(diary.getComment().isEmpty()) { cursor1.insertText(tr("Add your own text here...")); } else { cursor1.insertHtml(diary.getComment()); } cursor.setPosition(cursor1.position()+1); } if(!diary.getWpts().isEmpty()) { QList<CWpt*>& wpts = diary.getWpts(); cursor.insertText(tr("Waypoints"),fmtCharHeading2); QTextTable * table = cursor.insertTable(wpts.count()+1, eMax, fmtTableStandard); diary.tblWpt = table; table->cellAt(0,eSym).setFormat(fmtCharHeader); table->cellAt(0,eInfo).setFormat(fmtCharHeader); table->cellAt(0,eComment).setFormat(fmtCharHeader); table->cellAt(0,eInfo).firstCursorPosition().insertText(tr("Info")); table->cellAt(0,eComment).firstCursorPosition().insertText(tr("Comment")); cnt = 1; qSort(wpts.begin(), wpts.end(), qSortWptLessTime); foreach(CWpt * wpt, wpts) { table->cellAt(cnt,eSym).firstCursorPosition().insertImage(wpt->getIcon().toImage().scaledToWidth(16, Qt::SmoothTransformation)); table->cellAt(cnt,eInfo).firstCursorPosition().insertText(wpt->getName() + "\n" + wpt->getInfo(), fmtCharStandard); QTextCursor c = table->cellAt(cnt,eComment).firstCursorPosition(); c.setCharFormat(fmtCharStandard); c.setBlockFormat(fmtBlockStandard); c.insertHtml(wpt->getComment()); if(wpt->isGeoCache()) { hasGeoCaches = true; } cnt++; }
bool Converter::convertTable(const QDomElement &element) { /** * Find out dimension of the table */ int rowCounter = 0; int columnCounter = 0; QQueue<QDomNode> nodeQueue; enqueueNodeList(nodeQueue, element.childNodes()); while (!nodeQueue.isEmpty()) { QDomElement el = nodeQueue.dequeue().toElement(); if (el.isNull()) continue; if (el.tagName() == QLatin1String("table-row")) { rowCounter++; int counter = 0; QDomElement columnElement = el.firstChildElement(); while (!columnElement.isNull()) { if (columnElement.tagName() == QLatin1String("table-cell")) { counter++; } columnElement = columnElement.nextSiblingElement(); } columnCounter = qMax(columnCounter, counter); } else if (el.tagName() == QLatin1String("table-header-rows")) { enqueueNodeList(nodeQueue, el.childNodes()); } } /** * Create table */ QTextTable *table = m_Cursor->insertTable(rowCounter, columnCounter); firstTime=false; m_Cursor->movePosition(QTextCursor::End); /** * Fill table */ nodeQueue.clear(); enqueueNodeList(nodeQueue, element.childNodes()); QTextTableFormat tableFormat; rowCounter = 0; while (!nodeQueue.isEmpty()) { QDomElement el = nodeQueue.dequeue().toElement(); if (el.isNull()) continue; if (el.tagName() == QLatin1String("table-row")) { int columnCounter = 0; QDomElement columnElement = el.firstChildElement(); while (!columnElement.isNull()) { if (columnElement.tagName() == QLatin1String("table-cell")) { const StyleFormatProperty property = m_StyleInformation->styleProperty(columnElement.attribute("style-name")); QTextBlockFormat format; property.applyTableCell(&format); QDomElement paragraphElement = columnElement.firstChildElement(); while (!paragraphElement.isNull()) { if (paragraphElement.tagName() == QLatin1String("p")) { QTextTableCell cell = table->cellAt(rowCounter, columnCounter); // Insert a frame into the cell and work on that, so we can handle // different parts of the cell having different block formatting QTextCursor cellCursor = cell.lastCursorPosition(); QTextFrameFormat frameFormat; //frameFormat.setMargin(1); // TODO: this shouldn't be hard coded //todo: too much is created here - why? QTextFrame *frame = cellCursor.insertFrame(frameFormat); QTextCursor frameCursor = frame->firstCursorPosition(); frameCursor.setBlockFormat(format); if (!convertParagraph(&frameCursor, paragraphElement, format)) return false; } else if (paragraphElement.tagName() == QLatin1String("list")) { QTextTableCell cell = table->cellAt(rowCounter, columnCounter); // insert a list into the cell QTextCursor cellCursor = cell.lastCursorPosition(); if (!convertList(&cellCursor, paragraphElement)) { return false; } } paragraphElement = paragraphElement.nextSiblingElement(); } columnCounter++; } columnElement = columnElement.nextSiblingElement(); } rowCounter++; } else if (el.tagName() == QLatin1String("table-column")) { const StyleFormatProperty property = m_StyleInformation->styleProperty(el.attribute("style-name")); const QString tableColumnNumColumnsRepeated = el.attribute("number-columns-repeated", "1"); int numColumnsToApplyTo = tableColumnNumColumnsRepeated.toInt(); for (int i = 0; i < numColumnsToApplyTo; ++i) { property.applyTableColumn(&tableFormat); } } } table->setFormat(tableFormat); return true; }