C++/Qt/QTextBlockFormat

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

Text block format

  
/****************************************************************************
**
** 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$
**
****************************************************************************/
#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();
    QTextCursor cursor(editor->textCursor());
    cursor.movePosition(QTextCursor::Start); 
    QTextBlockFormat blockFormat = cursor.blockFormat();
    blockFormat.setTopMargin(4);
    blockFormat.setLeftMargin(4);
    blockFormat.setRightMargin(4);
    blockFormat.setBottomMargin(4);
    cursor.setBlockFormat(blockFormat);
    cursor.insertText(tr("This contains plain text inside a "
                         "text block with margins to keep it separate "
                         "from other parts of the document."));
    cursor.insertBlock();

    QTextBlockFormat backgroundFormat = blockFormat;
    backgroundFormat.setBackground(QColor("lightGray"));
    cursor.setBlockFormat(backgroundFormat);
    cursor.insertText(tr("The background color of a text block can be "
                         "changed to highlight text."));
    cursor.insertBlock();
    QTextBlockFormat rightAlignedFormat = blockFormat;
    rightAlignedFormat.setAlignment(Qt::AlignRight);
    cursor.setBlockFormat(rightAlignedFormat);
    cursor.insertText(tr("The alignment of the text within a block is "
                         "controlled by the alignment properties of "
                         "the block itself. This text block is "
                         "right-aligned."));
    cursor.insertBlock();
    QTextBlockFormat paragraphFormat = blockFormat;
    paragraphFormat.setAlignment(Qt::AlignJustify);
    paragraphFormat.setTextIndent(32);
    cursor.setBlockFormat(paragraphFormat);
    cursor.insertText(tr("Text can be formatted so that the first "
                         "line in a paragraph has its own margin. "
                         "This makes the text more readable."));
    cursor.insertBlock();
    QTextBlockFormat reverseFormat = blockFormat;
    reverseFormat.setAlignment(Qt::AlignJustify);
    reverseFormat.setTextIndent(32);
    cursor.setBlockFormat(reverseFormat);
    cursor.insertText(tr("The direction of the text can be reversed. "
                         "This is useful for right-to-left "
                         "languages."));
    editor->setWindowTitle(tr("Text Block Formats"));
    editor->resize(480, 480);
    editor->show();
    
    return app.exec();
}


Text block fragments

  
/****************************************************************************
**
** 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$
**
****************************************************************************/
#ifndef XMLWRITER_H
#define XMLWRITER_H
#include <QDomDocument>
class QTextDocument;
class XmlWriter
{
public:
    XmlWriter(QTextDocument *document) : textDocument(document) {}
    QDomDocument *toXml();
private:
    void readFragment(const QTextBlock &currentBlock, QDomElement blockElement,
                      QDomDocument *document);
    void processBlock(const QTextBlock &currentBlock);
    void processFragment(const QTextFragment &currentFragment);
    QDomDocument *document;
    QTextDocument *textDocument;
};
#endif


#include <QtGui>
#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 currentBlock = textDocument->begin();
    while (currentBlock.isValid()) {
        QDomElement blockElement = document->createElement("block");
        document->appendChild(blockElement);
        readFragment(currentBlock, blockElement, document);

        processBlock(currentBlock);

        currentBlock = currentBlock.next();
    }

    return document;
}
void XmlWriter::readFragment(const QTextBlock &currentBlock,
                             QDomElement blockElement,
                             QDomDocument *document)
{
 
    QTextBlock::iterator it;
    for (it = currentBlock.begin(); !(it.atEnd()); ++it) {
        QTextFragment currentFragment = it.fragment();
        if (currentFragment.isValid())
 
            processFragment(currentFragment);
 
        if (currentFragment.isValid()) {
            QDomElement fragmentElement = document->createElement("fragment");
            blockElement.appendChild(fragmentElement);
            fragmentElement.setAttribute("length", currentFragment.length());
            QDomText fragmentText = document->createTextNode(currentFragment.text());
            fragmentElement.appendChild(fragmentText);
        }
    }
 
}
void XmlWriter::processBlock(const QTextBlock &currentBlock)
{
}
void XmlWriter::processFragment(const QTextFragment &currentFragment)
{
}


#ifndef WINDOW_H
#define WINDOW_H
#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;
};
#endif


#include <QtGui>
#include "mainwindow.h"
#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 << domDocument->toByteArray(1);
        return true;
    }
    else
        return false;
}


#include <QtGui>
#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();
}