C++/Qt/QTextDocument

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Adding resource to QTextDocument

<source lang="cpp"> /****************************************************************************

    • Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
    • All rights reserved.
    • Contact: Nokia Corporation (qt-info@nokia.com)
    • This file is part of the documentation of the Qt Toolkit.
    • $QT_BEGIN_LICENSE:LGPL$
    • Commercial Usage
    • Licensees holding valid Qt Commercial licenses may use this file in
    • accordance with the Qt Commercial License Agreement provided with the
    • Software or, alternatively, in accordance with the terms contained in
    • a written agreement between you and Nokia.
    • GNU Lesser General Public License Usage
    • Alternatively, this file may be used under the terms of the GNU Lesser
    • General Public License version 2.1 as published by the Free Software
    • Foundation and appearing in the file LICENSE.LGPL included in the
    • packaging of this file. Please review the following information to
    • ensure the GNU Lesser General Public License version 2.1 requirements
    • will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
    • In addition, as a special exception, Nokia gives you certain additional
    • rights. These rights are described in the Nokia Qt LGPL Exception
    • version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
    • GNU General Public License Usage
    • Alternatively, this file may be used under the terms of the GNU
    • General Public License version 3.0 as published by the Free Software
    • Foundation and appearing in the file LICENSE.GPL included in the
    • packaging of this file. Please review the following information to
    • ensure the GNU General Public License version 3.0 requirements will be
    • met: http://www.gnu.org/copyleft/gpl.html.
    • If you have questions regarding the use of this file, please contact
    • Nokia at qt-info@nokia.com.
    • $QT_END_LICENSE$
                                                                                                                                                        • /
  1. include <QtGui>

QString tr(const char *text) {

   return QApplication::translate(text, text);

} int main(int argc, char *argv[]) {

   QApplication app(argc, argv);
   QTextEdit *editor = new QTextEdit;
   QTextDocument *document = new QTextDocument(editor);
   QTextCursor cursor(document);
   QImage image(64, 64, QImage::Format_RGB32);
   image.fill(qRgb(255, 160, 128));

//! [Adding a resource]

   document->addResource(QTextDocument::ImageResource,
       QUrl("mydata://image.png"), QVariant(image));

//! [Adding a resource] //! [Inserting an image with a cursor]

   QTextImageFormat imageFormat;
   imageFormat.setName("mydata://image.png");
   cursor.insertImage(imageFormat);

//! [Inserting an image with a cursor]

   cursor.insertBlock();
   cursor.insertText("Code less. Create more.");
   editor->setDocument(document);
   editor->setWindowTitle(tr("Text Document Images"));
   editor->resize(320, 480);
   editor->show();

//! [Inserting an image using HTML]

   editor->append("<img src=\"mydata://image.png\" />");

//! [Inserting an image using HTML]

   return app.exec();

}


 </source>


Draw QTextDocument with QTextDocument

<source lang="cpp">

Foundations of Qt Development\Chapter07\text\main.cpp /*

* Copyright (c) 2006-2007, Johan Thelin
* 
* All rights reserved.
* 
* Redistribution and use in source and binary forms, with or without modification, 
* are permitted provided that the following conditions are met:
* 
*     * Redistributions of source code must retain the above copyright notice, 
*       this list of conditions and the following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright notice,  
*       this list of conditions and the following disclaimer in the documentation 
*       and/or other materials provided with the distribution.
*     * Neither the name of APress nor the names of its contributors 
*       may be used to endorse or promote products derived from this software 
*       without specific prior written permission.
* 
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
  1. include <QApplication>
  2. include <QPixmap>
  3. include <QPainter>
  4. include <QTextDocument>

int main( int argc, char **argv ) {

 QApplication app( argc, argv );
 QPixmap pixmap( 200, 330 );
 pixmap.fill( Qt::white );
 QPainter painter( &pixmap );
 painter.setPen( Qt::black );
   
 QPoint point = QPoint( 10, 20 );
 painter.drawText( point, "You can draw text from a point..." );
 painter.drawLine( point+QPoint(-5, 0), point+QPoint(5, 0) );
 painter.drawLine( point+QPoint(0, -5), point+QPoint(0, 5) );
 
 QRect rect = QRect(10, 30, 180, 20);
 painter.drawText( rect, Qt::AlignCenter, 
                   "...or you can draw it inside a rectangle." );
 painter.drawRect( rect );
 
 rect.translate( 0, 30 );
 
 QFont font = QApplication::font();
 font.setPixelSize( rect.height() );
 painter.setFont( font );
 
 painter.drawText( rect, Qt::AlignRight, "Right." );
 painter.drawText( rect, Qt::AlignLeft, "Left." );
 painter.drawRect( rect );
 
 rect.translate( 0, rect.height()+10 );
 rect.setHeight( QFontMetrics( font ).height() );
 painter.drawText( rect, Qt::AlignRight, "Right." );
 painter.drawText( rect, Qt::AlignLeft, "Left." );
 painter.drawRect( rect );
 
 QTextDocument doc;
doc.setHtml( "

A QTextDocument can be used to present formatted text " "in a nice way.

" "

It can be formatted " "in different ways.

" "

The text can be really long and contain many " "paragraphs. It is properly wrapped and such...

" );
 rect.translate( 0, rect.height()+10 );
 rect.setHeight( 160 );
 doc.setTextWidth( rect.width() );
 painter.save();
 painter.translate( rect.topLeft() );
 doc.drawContents( &painter, rect.translated( -rect.topLeft() ) );
 painter.restore();
 painter.drawRect( rect );
 rect.translate( 0, 160 );
 rect.setHeight( doc.size().height()-160 );
 painter.setBrush( Qt::gray );
 painter.drawRect( rect );
 pixmap.save( "text.png" );
 return 0;

}


 </source>


Text document blocks

<source lang="cpp"> /****************************************************************************

    • Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
    • All rights reserved.
    • Contact: Nokia Corporation (qt-info@nokia.com)
    • This file is part of the documentation of the Qt Toolkit.
    • $QT_BEGIN_LICENSE:LGPL$
    • Commercial Usage
    • Licensees holding valid Qt Commercial licenses may use this file in
    • accordance with the Qt Commercial License Agreement provided with the
    • Software or, alternatively, in accordance with the terms contained in
    • a written agreement between you and Nokia.
    • GNU Lesser General Public License Usage
    • Alternatively, this file may be used under the terms of the GNU Lesser
    • General Public License version 2.1 as published by the Free Software
    • Foundation and appearing in the file LICENSE.LGPL included in the
    • packaging of this file. Please review the following information to
    • ensure the GNU Lesser General Public License version 2.1 requirements
    • will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
    • In addition, as a special exception, Nokia gives you certain additional
    • rights. These rights are described in the Nokia Qt LGPL Exception
    • version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
    • GNU General Public License Usage
    • Alternatively, this file may be used under the terms of the GNU
    • General Public License version 3.0 as published by the Free Software
    • Foundation and appearing in the file LICENSE.GPL included in the
    • packaging of this file. Please review the following information to
    • ensure the GNU General Public License version 3.0 requirements will be
    • met: http://www.gnu.org/copyleft/gpl.html.
    • If you have questions regarding the use of this file, please contact
    • Nokia at qt-info@nokia.com.
    • $QT_END_LICENSE$
                                                                                                                                                        • /
  1. ifndef XMLWRITER_H
  2. define XMLWRITER_H
  3. include <QDomDocument>

class QTextDocument; class XmlWriter { public:

   XmlWriter(QTextDocument *document) : textDocument(document) {}
   QDomDocument *toXml();

private:

   void createItems(QDomElement &parent, const QTextBlock &block);
   QDomDocument *document;
   QTextDocument *textDocument;

};

  1. endif


  1. include <QtGui>
  2. include "xmlwriter.h"

QDomDocument *XmlWriter::toXml() {

   QDomImplementation implementation;
   QDomDocumentType docType = implementation.createDocumentType(
       "scribe-document", "scribe", "qt,nokia.com/scribe");
   document = new QDomDocument(docType);
   // ### This processing instruction is required to ensure that any kind
   // of encoding is given when the document is written.
   QDomProcessingInstruction process = document->createProcessingInstruction(
       "xml", "version=\"1.0\" encoding=\"utf-8\"");
   document->appendChild(process);
   QDomElement documentElement = document->createElement("document");
   document->appendChild(documentElement);
   QTextBlock firstBlock = textDocument->begin();
   createItems(documentElement, firstBlock);
   return document;

} void XmlWriter::createItems(QDomElement &parent, const QTextBlock &block) {

   QTextBlock currentBlock = block;
   while (currentBlock.isValid()) {
       QDomElement blockElement = document->createElement("block");
       blockElement.setAttribute("length", currentBlock.length());
       parent.appendChild(blockElement);
       if (!(currentBlock.text().isNull())) {
           QDomText textNode = document->createTextNode(currentBlock.text());
           blockElement.appendChild(textNode);
       }
       currentBlock = currentBlock.next();
   }

}


  1. ifndef WINDOW_H
  2. define WINDOW_H
  3. include <QMainWindow>

class QTextEdit; class MainWindow : public QMainWindow {

   Q_OBJECT

public:

   MainWindow();

public slots:

   void insertCalendar();
   void saveFile();

private:

   bool writeXml(const QString &fileName);
   QTextEdit *editor;

};

  1. endif


  1. include <QtGui>
  2. include "mainwindow.h"
  3. include "xmlwriter.h"

MainWindow::MainWindow() {

   QMenu *fileMenu = new QMenu(tr("&File"));
   QAction *saveAction = fileMenu->addAction(tr("&Save..."));
   saveAction->setShortcut(tr("Ctrl+S"));
   QAction *quitAction = fileMenu->addAction(tr("E&xit"));
   quitAction->setShortcut(tr("Ctrl+Q"));
   QMenu *insertMenu = new QMenu(tr("&Insert"));
   QAction *calendarAction = insertMenu->addAction(tr("&Calendar"));
   calendarAction->setShortcut(tr("Ctrl+I"));
   menuBar()->addMenu(fileMenu);
   menuBar()->addMenu(insertMenu);
   editor = new QTextEdit(this);
   connect(saveAction, SIGNAL(triggered()), this, SLOT(saveFile()));
   connect(quitAction, SIGNAL(triggered()), this, SLOT(close()));
   connect(calendarAction, SIGNAL(triggered()), this, SLOT(insertCalendar()));
   setCentralWidget(editor);
   setWindowTitle(tr("Text Document Writer"));

} void MainWindow::saveFile() {

   QString fileName = QFileDialog::getSaveFileName(this,
       tr("Save document as:"), "", tr("XML (*.xml)"));
   if (!fileName.isEmpty()) {
       if (writeXml(fileName))
           setWindowTitle(fileName);
       else
           QMessageBox::warning(this, tr("Warning"),
               tr("Failed to save the document."), QMessageBox::Cancel,
               QMessageBox::NoButton);
   }

} void MainWindow::insertCalendar() {

   QTextCursor cursor(editor->textCursor());
   cursor.movePosition(QTextCursor::Start); 
   QTextCharFormat format(cursor.charFormat());
   format.setFontFamily("Courier");
   
   QTextCharFormat boldFormat = format;
   boldFormat.setFontWeight(QFont::Bold);
   cursor.insertBlock();
   cursor.insertText(" ", boldFormat);
   QDate date = QDate::currentDate();
   int year = date.year(), month = date.month();
   for (int weekDay = 1; weekDay <= 7; ++weekDay) {
       cursor.insertText(QString("%1 ").arg(QDate::shortDayName(weekDay), 3),
           boldFormat);
   }
   cursor.insertBlock();
   cursor.insertText(" ", format);
   for (int column = 1; column < QDate(year, month, 1).dayOfWeek(); ++column) {
       cursor.insertText("    ", format);
   }
   for (int day = 1; day <= date.daysInMonth(); ++day) {

       int weekDay = QDate(year, month, day).dayOfWeek();
       if (QDate(year, month, day) == date)
           cursor.insertText(QString("%1 ").arg(day, 3), boldFormat);
       else
           cursor.insertText(QString("%1 ").arg(day, 3), format);
       if (weekDay == 7) {
           cursor.insertBlock();
           cursor.insertText(" ", format);
       }

   }

} bool MainWindow::writeXml(const QString &fileName) {

   XmlWriter documentWriter(editor->document());
   QDomDocument *domDocument = documentWriter.toXml();
   QFile file(fileName);
   if (file.open(QFile::WriteOnly)) {
       QTextStream textStream(&file);
       textStream.setCodec(QTextCodec::codecForName("UTF-8"));
       
       textStream << domDocument->toString(1).toUtf8();
       file.close();
       return true;
   }
   else
       return false;

}


  1. include <QtGui>
  2. include "mainwindow.h"

int main(int argc, char *argv[]) {

   QApplication app(argc, argv);
   MainWindow *window = new MainWindow;
   window->resize(640, 480);
   window->show();
   return app.exec();

}


 </source>


Text document selection

<source lang="cpp"> /****************************************************************************

    • Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
    • All rights reserved.
    • Contact: Nokia Corporation (qt-info@nokia.com)
    • This file is part of the documentation of the Qt Toolkit.
    • $QT_BEGIN_LICENSE:LGPL$
    • Commercial Usage
    • Licensees holding valid Qt Commercial licenses may use this file in
    • accordance with the Qt Commercial License Agreement provided with the
    • Software or, alternatively, in accordance with the terms contained in
    • a written agreement between you and Nokia.
    • GNU Lesser General Public License Usage
    • Alternatively, this file may be used under the terms of the GNU Lesser
    • General Public License version 2.1 as published by the Free Software
    • Foundation and appearing in the file LICENSE.LGPL included in the
    • packaging of this file. Please review the following information to
    • ensure the GNU Lesser General Public License version 2.1 requirements
    • will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
    • In addition, as a special exception, Nokia gives you certain additional
    • rights. These rights are described in the Nokia Qt LGPL Exception
    • version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
    • GNU General Public License Usage
    • Alternatively, this file may be used under the terms of the GNU
    • General Public License version 3.0 as published by the Free Software
    • Foundation and appearing in the file LICENSE.GPL included in the
    • packaging of this file. Please review the following information to
    • ensure the GNU General Public License version 3.0 requirements will be
    • met: http://www.gnu.org/copyleft/gpl.html.
    • If you have questions regarding the use of this file, please contact
    • Nokia at qt-info@nokia.com.
    • $QT_END_LICENSE$
                                                                                                                                                        • /
  1. ifndef WINDOW_H
  2. define WINDOW_H
  3. include <QMainWindow>
  4. include <QTextDocumentFragment>

class QAction; class QTextDocument; class QTextEdit; class MainWindow : public QMainWindow {

   Q_OBJECT

public:

   MainWindow();

public slots:

   void cutSelection();
   void copySelection();
   void openFile();
   void pasteSelection();
   void selectWord();
   void selectLine();
   void selectBlock();
   void selectFrame();
   void updateMenus();

private:

   QAction *cutAction;
   QAction *copyAction;
   QAction *pasteAction;
   QString currentFile;
   QTextEdit *editor;
   QTextDocument *document;
   QTextDocumentFragment selection;

};

  1. endif


  1. include <QtGui>
  2. include "mainwindow.h"

MainWindow::MainWindow() {

   QMenu *fileMenu = new QMenu(tr("&File"));
   fileMenu->addAction(tr("&Open..."), this, SLOT(openFile()),
                       QKeySequence(tr("Ctrl+O", "File|Open")));
   QAction *quitAction = fileMenu->addAction(tr("E&xit"), this, SLOT(close()));
   quitAction->setShortcut(tr("Ctrl+Q"));
   QMenu *editMenu = new QMenu(tr("&Edit"));
   cutAction = editMenu->addAction(tr("Cu&t"), this, SLOT(cutSelection()));
   cutAction->setShortcut(tr("Ctrl+X"));
   cutAction->setEnabled(false);
   copyAction = editMenu->addAction(tr("&Copy"), this, SLOT(copySelection()));
   copyAction->setShortcut(tr("Ctrl+C"));
   copyAction->setEnabled(false);
   pasteAction = editMenu->addAction(tr("&Paste"), this, SLOT(pasteSelection()));
   pasteAction->setShortcut(tr("Ctrl+V"));
   pasteAction->setEnabled(false);
   QMenu *selectMenu = new QMenu(tr("&Select"));
   selectMenu->addAction(tr("&Word"), this, SLOT(selectWord()));
   selectMenu->addAction(tr("&Line"), this, SLOT(selectLine()));
   selectMenu->addAction(tr("&Block"), this, SLOT(selectBlock()));
   selectMenu->addAction(tr("&Frame"), this, SLOT(selectFrame()));
   menuBar()->addMenu(fileMenu);
   menuBar()->addMenu(editMenu);
   menuBar()->addMenu(selectMenu);
   editor = new QTextEdit(this);
   document = new QTextDocument(this);
   editor->setDocument(document);
   connect(editor, SIGNAL(selectionChanged()), this, SLOT(updateMenus()));
   setCentralWidget(editor);
   setWindowTitle(tr("Text Document Writer"));

} void MainWindow::openFile() {

   QString fileName = QFileDialog::getOpenFileName(this,
       tr("Open file"), currentFile, "HTML files (*.html);;Text files (*.txt)");
   
   if (!fileName.isEmpty()) {
       QFileInfo info(fileName);
       if (info.completeSuffix() == "html") {
           QFile file(fileName);
           
           if (file.open(QFile::ReadOnly)) {
               editor->setHtml(QString(file.readAll()));
               file.close();
               currentFile = fileName;
           }
       } else if (info.completeSuffix() == "txt") {
           QFile file(fileName);
           
           if (file.open(QFile::ReadOnly)) {
               editor->setPlainText(file.readAll());
               file.close();
               currentFile = fileName;
           }
       }
   }

} void MainWindow::cutSelection() {

   QTextCursor cursor = editor->textCursor();
   if (cursor.hasSelection()) {
       selection = cursor.selection();
       cursor.removeSelectedText();
   }

} void MainWindow::copySelection() {

   QTextCursor cursor = editor->textCursor();
   if (cursor.hasSelection()) {
       selection = cursor.selection();
       cursor.clearSelection();
   }

} void MainWindow::pasteSelection() {

   QTextCursor cursor = editor->textCursor();
   cursor.insertFragment(selection);

} void MainWindow::selectWord() {

   QTextCursor cursor = editor->textCursor();
   QTextBlock block = cursor.block();
   cursor.beginEditBlock();
   cursor.movePosition(QTextCursor::StartOfWord);
   cursor.movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
   cursor.endEditBlock();
   editor->setTextCursor(cursor);

} void MainWindow::selectLine() {

   QTextCursor cursor = editor->textCursor();
   QTextBlock block = cursor.block();
   cursor.beginEditBlock();
   cursor.movePosition(QTextCursor::StartOfLine);
   cursor.movePosition(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
   cursor.endEditBlock();
   editor->setTextCursor(cursor);

} void MainWindow::selectBlock() {

   QTextCursor cursor = editor->textCursor();
   QTextBlock block = cursor.block();
   cursor.beginEditBlock();
   cursor.movePosition(QTextCursor::StartOfBlock);
   cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
   cursor.endEditBlock();
   editor->setTextCursor(cursor);

} void MainWindow::selectFrame() {

   QTextCursor cursor = editor->textCursor();
   QTextFrame *frame = cursor.currentFrame();
   cursor.beginEditBlock();
   cursor.setPosition(frame->firstPosition());
   cursor.setPosition(frame->lastPosition(), QTextCursor::KeepAnchor);
   cursor.endEditBlock();
   editor->setTextCursor(cursor);

} void MainWindow::updateMenus() {

   QTextCursor cursor = editor->textCursor();
   cutAction->setEnabled(cursor.hasSelection());
   copyAction->setEnabled(cursor.hasSelection());
   pasteAction->setEnabled(!selection.isEmpty());

}


  1. include <QtGui>
  2. include "mainwindow.h"

int main(int argc, char *argv[]) {

   QApplication app(argc, argv);
   MainWindow *window = new MainWindow;
   window->resize(640, 480);
   window->show();
   return app.exec();

}


 </source>