Пример Order Form
|
| фрейм с referenceFrameFormat | |
| block | A company |
| block | |
| block | 321 City Street |
| block | |
| block | Industry Park |
| block | |
| block | Another country |
Это выполняется следующим кодом:
QTextFrame *topFrame = cursor.currentFrame();
QTextFrameFormat topFrameFormat = topFrame->frameFormat();
topFrameFormat.setPadding(16);
topFrame->setFrameFormat(topFrameFormat);
QTextCharFormat textFormat;
QTextCharFormat boldFormat;
boldFormat.setFontWeight(QFont::Bold);
QTextFrameFormat referenceFrameFormat;
referenceFrameFormat.setBorder(1);
referenceFrameFormat.setPadding(8);
referenceFrameFormat.setPosition(QTextFrameFormat::FloatRight);
referenceFrameFormat.setWidth(QTextLength(QTextLength::PercentageLength, 40));
cursor.insertFrame(referenceFrameFormat);
cursor.insertText("A company", boldFormat);
cursor.insertBlock();
cursor.insertText("321 City Street");
cursor.insertBlock();
cursor.insertText("Industry Park");
cursor.insertBlock();
cursor.insertText("Another country");
Заметьте, что topFrame это фрейм верхнего уровня в editor и не показан в структуре документа.
Затем мы возвращаем cursor в его последнюю позицию в topFrame и заполняем имя клиента (предоставляется конструктором) и адрес - используя цикл foreach для обхода QString address.
cursor.setPosition(topFrame->lastPosition());
cursor.insertText(name, textFormat);
QString line;
foreach (line, address.split("\n")) {
cursor.insertBlock();
cursor.insertText(line);
}
Сейчас cursor вернулся в topFrame и структура документа для части кода выше следующая:
| block | Donald |
| block | 47338 Park Avenue |
| block | Big City |
С целью расположения с интервалами мы вызываем insertBlock() дважды. currentDate() получается и отображается. Мы используем setWidth() для увеличения ширины bodyFrameFormat и мы вставляем новый фрейм с этой шириной.
cursor.insertBlock();
cursor.insertBlock();
QDate date = QDate::currentDate();
cursor.insertText(tr("Date: %1").arg(date.toString("d MMMM yyyy")),
textFormat);
cursor.insertBlock();
QTextFrameFormat bodyFrameFormat;
bodyFrameFormat.setWidth(QTextLength(QTextLength::PercentageLength, 100));
cursor.insertFrame(bodyFrameFormat);
Следующий код вставляет стандартный текст в форму заказа.
cursor.insertText(tr("I would like to place an order for the following "
"items:"), textFormat);
cursor.insertBlock();
cursor.insertBlock();
Эта часть структуры документа сейчас содержит дату, фрейм с bodyFrameFormat, так же как и стандартный текст.
| block | |
| block | |
| block | Date: 25 May 2007 |
| block | |
| фрейм с bodyFrameFormat | |
| block | I would like to place an order for the following items: |
| block | |
| block |
Объект QTextTableFormat orderTableFormat используется для хранения типа элемента и заказанное количество.
QTextTableFormat orderTableFormat;
orderTableFormat.setAlignment(Qt::AlignHCenter);
QTextTable *orderTable = cursor.insertTable(1, 2, orderTableFormat);
QTextFrameFormat orderFrameFormat = cursor.currentFrame()->frameFormat();
orderFrameFormat.setBorder(1);
cursor.currentFrame()->setFrameFormat(orderFrameFormat);
Мы используем cellAt() что бы установить заголовки для orderTable.
cursor = orderTable->cellAt(0, 0).firstCursorPosition();
cursor.insertText(tr("Product"), boldFormat);
cursor = orderTable->cellAt(0, 1).firstCursorPosition();
cursor.insertText(tr("Quantity"), boldFormat);
Затем мы перебираем QList объектов QPair что бы заселить orderTable.
for (int i = 0; i < orderItems.count(); ++i) {
QPair<QString,int> item = orderItems[i];
int row = orderTable->rows();
orderTable->insertRows(row, 1);
cursor = orderTable->cellAt(row, 0).firstCursorPosition();
cursor.insertText(item.first, textFormat);
cursor = orderTable->cellAt(row, 1).firstCursorPosition();
cursor.insertText(QString("%1").arg(item.second), textFormat);
}
Результирующая структура документа для этой секции следующая::
| orderTable с orderTableFormat | |
| block | Product |
| block | Quantity |
| block | T-shirt |
| block | 4 |
| block | Badge |
| block | 3 |
| block | Reference book |
| block | 2 |
| block | Coffee cup |
| block | 5 |
Затем cursor возвращается в topFrame в последнюю позицию lastPosition() и вставляется дополнительный стандартный текст.
cursor.setPosition(topFrame->lastPosition());
cursor.insertBlock();
cursor.insertText(tr("Please update my records to take account of the "
"following privacy information:"));
cursor.insertBlock();
Другая QTextTable вставляется для отображения предпочтений клиента относительно предложений.
QTextTable *offersTable = cursor.insertTable(2, 2);
cursor = offersTable->cellAt(0, 1).firstCursorPosition();
cursor.insertText(tr("I want to receive more information about your "
"company's products and special offers."), textFormat);
cursor = offersTable->cellAt(1, 1).firstCursorPosition();
cursor.insertText(tr("I do not want to receive any promotional information "
"from your company."), textFormat);
if (sendOffers)
cursor = offersTable->cellAt(0, 0).firstCursorPosition();
else
cursor = offersTable->cellAt(1, 0).firstCursorPosition();
cursor.insertText("X", boldFormat);
Структура документа для этой части будет:
| block | |
| block | Please update my... |
| block | |
| offersTable | |
| block | I want to receive... |
| block | I do not want to recieve... |
| block | X |
cursor перемещается для вставки "Sincerely" вместе с именем клиента. Еще несколько блоков вставляются с целью отступа. printAction разблокируется что бы показать что форма заказа может быть теперь распечатана.
cursor.setPosition(topFrame->lastPosition());
cursor.insertBlock();
cursor.insertText(tr("Sincerely,"), textFormat);
cursor.insertBlock();
cursor.insertBlock();
cursor.insertBlock();
cursor.insertText(name);
printAction->setEnabled(true);
}
Нижняя часть структуры документа:
| block | |
| block | Sincerely, |
| block | |
| block | |
| block | |
| block | Donald |
Функция createSample() используется с целью иллюстрации для создания примера формы заказа.
void MainWindow::createSample()
{
DetailsDialog dialog("Dialog with default values", this);
createLetter("Mr. Smith", "12 High Street\nSmall Town\nThis country",
dialog.orderItems(), true);
}
Функция openDialog() открывает объект DetailsDialog. Если подробности в dialog принимаются, функция createLetter() вызывается с использованием параметров извлеченных из dialog.
void MainWindow::openDialog()
{
DetailsDialog dialog(tr("Enter Customer Details"), this);
if (dialog.exec() == QDialog::Accepted)
createLetter(dialog.senderName(), dialog.senderAddress(),
dialog.orderItems(), dialog.sendOffers());
}
Для того, чтобы распечатать форму заказа, включается функция printFile() как показано ниже:
void MainWindow::printFile()
{
#ifndef QT_NO_PRINTER
QTextEdit *editor = static_cast<QTextEdit*>(letters->currentWidget());
QPrinter printer;
[fuzzy] QPrintDialog *dlg = new QPrintDialog(&printer, this);
dialog->setWindowTitle(tr("Print Document"));
if (editor->textCursor().hasSelection())
dialog->addEnabledOption(QAbstractPrintDialog::PrintSelection);
[fuzzy] if (dlg->exec() != QDialog::Accepted)
return;
editor->print(&printer);
#endif
}
Эта функция так же позволяет пользователю распечатать выделенную с помощью QTextCursor::hasSelection() область вместо печати всего документа.
Функция main() создает экземпляр MainWindow и устанавливает его размер равным 640x480 пикселов прежде чем вызвать функцию show() и функцию createSample().
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MainWindow window;
window.resize(640, 480);
window.show();
window.createSample();
return app.exec();
}
| Copyright © 2009 Nokia Corporation and/or its subsidiary(-ies) | Торговые марки | Qt 4.5.3 |
|
Попытка перевода Qt документации. Если есть желание присоединиться, или если есть замечания или пожелания, то заходите на форум: Перевод Qt документации на русский язык... Люди внесшие вклад в перевод: Команда переводчиков |