Writing ODF Files with Qt
Материал из Wiki.crossplatform.ru
Lit-uriy (Обсуждение | вклад) |
(перевод) |
||
Строка 7: | Строка 7: | ||
__TOC__ | __TOC__ | ||
</div> | </div> | ||
- | + | Осноным поводом к использованию автоматической генерации документов является создание отчетов. Возьмем, к примеру, магазин, в котором периодически происходит переучет товара и возникает необходимость узнать, действительно ли то, что лежит на полках, и то, что содержится в базе данных, есть одно и то же. Предположим, существует программа, которая обрабатывает базу данных и создает документ, содержащий план работы на день. Этот документ экспортируется в ODF и отсылается человеку, производящему проверку. | |
[[Image:qq27-phonebill-pretty.png|center]] | [[Image:qq27-phonebill-pretty.png|center]] | ||
- | + | В данной статье будет написан простой генератор отчетов, создающий телефонный счет. Мы создадим один класс, <tt>PhoneBillWriter</tt>, соответствующий телефонному счету для одного клиента, а вы можете модифицировать его, чтобы использовать как отправную точку для своих генераторов отчета. | |
- | === | + | ===Вначале=== |
- | + | Класс <tt>PhoneBillWriter</tt> будет иметь следующее определение: | |
<source lang="cpp-qt"> | <source lang="cpp-qt"> | ||
class PhoneBillWriter | class PhoneBillWriter | ||
Строка 38: | Строка 38: | ||
</source> | </source> | ||
- | + | Это даст нам способ создания одного экземпляра <tt>PhoneBillWriter</tt> для каждого счета, и наполнения его данными при помощи вызовов метода <tt>addPhoneCall()</tt>. Закончив вносить информацию, мы вызываем метод <tt>write()</tt> для того, чтобы закрыть текущий счет. Это классический пример использования паттерна "Строитель" ("Builder"). | |
- | + | Внутри себя класс пользуется [[Qt:Документация 4.3.2//qtextdocument | QTextDocument]], что видно в списке его закрытых членов. Класс [[Qt:Документация 4.3.2//qtextdocument | QTextDocument]] применяется во многих местах в Qt и ее виджетах. [[Qt:Документация 4.3.2//qtextedit | QTextEdit]] является одним из таких виджетов, и для доступа к документу в нем вызывается метод [[Qt:Документация 4.3.2//qtextedit#document | QTextEdit::document()]]. [[Qt:Документация 4.3.2//qtextdocument | QTextDocument]] - это текстовый документ, который может содержать структурированный текст, элементы разметки (полужирный шрифт, курсив) и многое другое. Для ознакомления см. демонстрационную программу Qt ''Text Edit''. | |
- | + | Класс [[Qt:Документация 4.3.2//qtextcursor | QTextCursor]] создан для того, чтобы предоставить способ управления содержимым текстового документа. В текстовых процессорах на экране есть мигающий курсор, который вы можете перемещать, и вводить текст, ориентируясь на него. Класс [[Qt:Документация 4.3.2//qtextcursor | QTextCursor]] служит достижению этого в вашей программе. | |
Версия 22:31, 24 апреля 2009
![]() | ![]() |
Qt Quarterly | Выпуск 27 | Документация |
by Thomas Zander
Предстоящий релиз Qt 4.5 отмечается появлением класса QTextDocumentWriter, который позволяет создавать файлы OpenDocument Format (ODF) из любого текстового документа Qt. Это открывает путь для автоматического создания и распространения документа в стандартном совместимом формате, который позволяет пользователю открыть его в различных текстовых редакторах.
Содержание |
Осноным поводом к использованию автоматической генерации документов является создание отчетов. Возьмем, к примеру, магазин, в котором периодически происходит переучет товара и возникает необходимость узнать, действительно ли то, что лежит на полках, и то, что содержится в базе данных, есть одно и то же. Предположим, существует программа, которая обрабатывает базу данных и создает документ, содержащий план работы на день. Этот документ экспортируется в ODF и отсылается человеку, производящему проверку.
В данной статье будет написан простой генератор отчетов, создающий телефонный счет. Мы создадим один класс, PhoneBillWriter, соответствующий телефонному счету для одного клиента, а вы можете модифицировать его, чтобы использовать как отправную точку для своих генераторов отчета.
Вначале
Класс PhoneBillWriter будет иметь следующее определение:
class PhoneBillWriter { public: PhoneBillWriter(const QString &client); ~PhoneBillWriter(); struct PhoneCall { QDateTime date; int duration; // in seconds int cost; // in euro-cents }; void addPhoneCall(const PhoneCall &call); void addGraph(QList<int> values, const QString &subtext); void write(const QString &fileName); private: QTextDocument * const m_document; QTextCursor m_cursor; };
Это даст нам способ создания одного экземпляра PhoneBillWriter для каждого счета, и наполнения его данными при помощи вызовов метода addPhoneCall(). Закончив вносить информацию, мы вызываем метод write() для того, чтобы закрыть текущий счет. Это классический пример использования паттерна "Строитель" ("Builder").
Внутри себя класс пользуется QTextDocument, что видно в списке его закрытых членов. Класс QTextDocument применяется во многих местах в Qt и ее виджетах. QTextEdit является одним из таких виджетов, и для доступа к документу в нем вызывается метод QTextEdit::document(). QTextDocument - это текстовый документ, который может содержать структурированный текст, элементы разметки (полужирный шрифт, курсив) и многое другое. Для ознакомления см. демонстрационную программу Qt Text Edit.
Класс QTextCursor создан для того, чтобы предоставить способ управления содержимым текстового документа. В текстовых процессорах на экране есть мигающий курсор, который вы можете перемещать, и вводить текст, ориентируясь на него. Класс QTextCursor служит достижению этого в вашей программе.
Writing the Bill
The approach used in this report writer is to create a QTextDocument in the constructor and add the header and nice formatting information that will be the same for each phone bill. Here's a simple implementation:
PhoneBillWriter::PhoneBillWriter(const QString &client) : m_document(new QTextDocument()), m_cursor(m_document) { m_cursor.insertText(QObject::tr( "Phone bill for %1\n").arg(client)); QTextTableFormat tableFormat; tableFormat.setCellPadding(5); tableFormat.setHeaderRowCount(1); tableFormat.setBorderStyle( QTextFrameFormat::BorderStyle_Solid); tableFormat.setWidth(QTextLength( QTextLength::PercentageLength, 100)); m_cursor.insertTable(1, 3, tableFormat); m_cursor.insertText(QObject::tr("Date")); m_cursor.movePosition(QTextCursor::NextCell); m_cursor.insertText(QObject::tr("Duration (sec)")); m_cursor.movePosition(QTextCursor::NextCell); m_cursor.insertText(QObject::tr("Cost")); } PhoneBillWriter::~PhoneBillWriter() { delete m_document; }
We start by adding a personal note and follow this with a table and the table header, which we fill them with the header labels. We don't need to specify in advance how many rows there are in the table.
The interesting bits are the m_cursor usage, which includes call to methods like insertTable() and insertText() to actually modify the document.
The QTextCursor also understands the concepts of selecting and removing text. A very powerful method on the cursor is movePosition(), to which you can pass one of the many values from its MoveOperation enum. This makes the class really behave like a cursor since all the usual navigation operations are there. In this case we use a navigation operation that's new in Qt 4.5: the NextCell operation moves the cursor to the start of the next table cell. As a result, the text passed to the following insertText() call will end up at the start of the table cell.
After setting up the header of the document we are ready to add actual user information to it. The caller can add individual phone calls using the addPhoneCall() method, passing in the individual fields that we show in the table.
void PhoneBillWriter::addPhoneCall( const PhoneBillWriter::PhoneCall &call) { QTextTable *table = m_cursor.currentTable(); table->appendRows(1); m_cursor.movePosition(QTextCursor::PreviousRow); m_cursor.movePosition(QTextCursor::NextCell); m_cursor.insertText(call.date.toString()); m_cursor.movePosition(QTextCursor::NextCell); m_cursor.insertText(QString::number(call.duration)); m_cursor.movePosition(QTextCursor::NextCell); QChar euro(0x20ac); m_cursor.insertText(QString("%1 %2").arg(euro) .arg(call.cost / (double) 100, 0, 'f', 2)); }
To show the phone call later, we add a row to our table and then continue to add the text to the document for each of the table cells. We call the appropriate QString methods to convert the integer data into text so we can fine-tune the way our data is shown. After all, the goal in our example is to make a pretty looking version of the raw data, and properly formatted text is the way to get there.
Having just text, even with tables, makes for boring reading. Adding graphs or other pictures is always a good way to make a document much more readable. This document talks about creating an ODF document, and the OpenDocument Format allows us to embed images into the final file, unlike HTML, for example.
In order to get the document into the final ODF file all we need to do is insert the image into the QTextDocument. It will not be a big surprise to learn that there is a QTextCursor::insertImage() method to do exactly this.
For our example document, we wanted to add a graph to show the amount of calls the client made in the last few months. For this the following code was used:
QList<int> callsPerMonth; callsPerMonth << 6 << 84 << 76 << 0 << 93 << 128 << 76 << 31 << 19 << 4 << 12 << 78; phoneBill.addGraph(callsPerMonth, "Your past usage:");
To actually create the graph, our solution is to create a QImage, use a QPainter to draw the values onto it, and then insert the image into the document at the right location.
void PhoneBillWriter::addGraph(QList<int> values, const QString &subtext) { const int columnSize = 10; int width = values.count() * columnSize; int max = 0; foreach (int x, values) max = qMax(max, x); QImage image(width, 100, QImage::Format_Mono); QPainter painter(&image); painter.fillRect(0, 0, image.width(), image.height(), Qt::white); // background for (int index = 0; index < values.count(); ++index) { // Adjust scale to our 100 pixel tall image: int height = values[index] * 100 / max; painter.fillRect(index * columnSize, image.height() - height, columnSize, height, Qt::black); } painter.end(); QTextCursor cursor(m_document); cursor.movePosition(QTextCursor::End); cursor.insertText(subtext); cursor.insertBlock(); cursor.insertImage(image); }
First, we calculate the required width of our graph based on the amount of values passed in. We choose to always have a height of 100 pixels and scale the values to fit in that range since most graphs are designed to show the relative sizes of the values to each other.
We use a monochrome format for the image, which means only two colors. You can use any image format you want for ODF, though. Two colors just seems enough for this use case.
After creation of the actual image we create a new QTextCursor and move it to the end of the document, where we insert the graph. An important note is that this cursor has a position that may be different from the m_cursor object. The reason for creating a new cursor here is to make sure the user can still call addPhoneCall() after the addGraph() call without affecting the positioning of the textual content.
The last part of our PhoneBillWriter class is to actually create the OpenDocument Format file from all the information we put into the writer object. The hard work is all done by the QTextDocumentWriter class, which is capable of writing to various formats, like plain text, HTML and ODF. The default is ODF, making the implementation trivial for us:
void PhoneBillWriter::write(const QString &fileName) { QTextDocumentWriter writer(fileName); writer.write(m_document); }
The above image shows the final document in OpenOffice.org. As it stands, it's intentionally simple for demonstration purposes, but there's a slightly more decorative example included alongside it in the archive available from the Qt Quarterly Web site.
Drawing Conclusions
The example we have presented is fairly simple and is focused on showing the basic ODF writing capabilities of QTextDocumentWriter rather than making the output look as pretty as possible.
Qt has plenty of features that we can use to improve the appearance of the phone bill and usefulness of the writer. For example, we could use the Qt SQL module to extract real information from an existing database and use QPainter to draw more visually appealing graphs and charts.
We could also create a nice frontend application to help the user create reports, or use Qt's ODF capabilities to do something completely unrelated to phone bill, reports or accounting. What you create with this new feature is up to you!
The source code for the example described in this article can be obtained from the Qt Quarterly Web site.