Viadeo Twitter Google Bookmarks ! Facebook Digg MySpace Yahoo MyWeb Blinklist Netvouz Reddit Simpy StumbleUpon Bookmarks Windows Live Favorites 
Logo Documentation Qt ·  Page d'accueil  ·  Toutes les classes  ·  Toutes les fonctions  ·  Vues d'ensemble  · 

Order Form Example


The Order Form example shows how to generate rich text documents by combining a simple template with data input by the user in a dialog. Data is extracted from a DetailsDialog object and displayed on a QTextEdit with a QTextCursor, using various formats. Each form generated is added to a QTabWidget for easy access.

DetailsDialog Definition

The DetailsDialog class is a subclass of QDialog, implementing a slot verify() to allow contents of the DetailsDialog to be verified later. This is further explained in DetailsDialog Implementation.

 class DetailsDialog : public QDialog

     DetailsDialog(const QString &title, QWidget *parent);

 public slots:
     void verify();

     QList<QPair<QString, int> > orderItems();
     QString senderName() const;
     QString senderAddress() const;
     bool sendOffers();

     void setupItemsTable();

     QLabel *nameLabel;
     QLabel *addressLabel;
     QCheckBox *offersCheckBox;
     QLineEdit *nameEdit;
     QStringList items;
     QTableWidget *itemsTable;
     QTextEdit *addressEdit;
     QDialogButtonBox *buttonBox;

The constructor of DetailsDialog accepts parameters title and parent. The class defines four getter functions: orderItems(), senderName(), senderAddress(), and sendOffers() to allow data to be accessed externally.

The class definition includes input widgets for the required fields, nameEdit and addressEdit. Also, a QCheckBox and a QDialogButtonBox are defined; the former to provide the user with the option to receive information on products and offers, and the latter to ensure that buttons used are arranged according to the user's native platform. In addition, a QTableWidget, itemsTable, is used to hold order details.

The screenshot below shows the DetailsDialog we intend to create.

DetailsDialog Implementation

The constructor of DetailsDialog instantiates the earlier defined fields and their respective labels. The label for offersCheckBox is set and the setupItemsTable() function is invoked to setup and populate itemsTable. The QDialogButtonBox object, buttonBox, is instantiated with OK and Cancel buttons. This buttonBox's accepted() and rejected() signals are connected to the verify() and reject() slots in DetailsDialog.

 DetailsDialog::DetailsDialog(const QString &title, QWidget *parent)
     : QDialog(parent)
     nameLabel = new QLabel(tr("Name:"));
     addressLabel = new QLabel(tr("Address:"));
     addressLabel->setAlignment(Qt::AlignLeft | Qt::AlignTop);

     nameEdit = new QLineEdit;
     addressEdit = new QTextEdit;

     offersCheckBox = new QCheckBox(tr("Send information about products and "
                                       "special offers"));


     buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok
                                      | QDialogButtonBox::Cancel);

     connect(buttonBox, SIGNAL(accepted()), this, SLOT(verify()));
     connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));

A QGridLayout is used to place all the objects on the DetailsDialog.

     QGridLayout *mainLayout = new QGridLayout;
     mainLayout->addWidget(nameLabel, 0, 0);
     mainLayout->addWidget(nameEdit, 0, 1);
     mainLayout->addWidget(addressLabel, 1, 0);
     mainLayout->addWidget(addressEdit, 1, 1);
     mainLayout->addWidget(itemsTable, 0, 2, 2, 1);
     mainLayout->addWidget(offersCheckBox, 2, 1, 1, 2);
     mainLayout->addWidget(buttonBox, 3, 0, 1, 3);


The setupItemsTable() function instantiates the QTableWidget object, itemsTable, and sets the number of rows based on the QStringList object, items, which holds the type of items ordered. The number of columns is set to 2, providing a "name" and "quantity" layout. A for loop is used to populate the itemsTable and the name item's flag is set to Qt::ItemIsEnabled or Qt::ItemIsSelectable. For demonstration purposes, the quantity item is set to a 1 and all items in the itemsTable have this value for quantity; but this can be modified by editing the contents of the cells at run time.

 void DetailsDialog::setupItemsTable()
     items << tr("T-shirt") << tr("Badge") << tr("Reference book")
           << tr("Coffee cup");

     itemsTable = new QTableWidget(items.count(), 2);

     for (int row = 0; row < items.count(); ++row) {
         QTableWidgetItem *name = new QTableWidgetItem(items[row]);
         name->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
         itemsTable->setItem(row, 0, name);
         QTableWidgetItem *quantity = new QTableWidgetItem("1");
         itemsTable->setItem(row, 1, quantity);

The orderItems() function extracts data from the itemsTable and returns it in the form of a QList<QPair<QString,int>> where each QPair corresponds to an item and the quantity ordered.

 QList<QPair<QString, int> > DetailsDialog::orderItems()
     QList<QPair<QString, int> > orderList;

     for (int row = 0; row < items.count(); ++row) {
         QPair<QString, int> item;
         item.first = itemsTable->item(row, 0)->text();
         int quantity = itemsTable->item(row, 1)->data(Qt::DisplayRole).toInt();
         item.second = qMax(0, quantity);

     return orderList;

The senderName() function is used to return the value of the QLineEdit used to store the name field for the order form.

 QString DetailsDialog::senderName() const
     return nameEdit->text();

The senderAddress() function is used to return the value of the QTextEdit containing the address for the order form.

 QString DetailsDialog::senderAddress() const
     return addressEdit->toPlainText();

The sendOffers() function is used to return a true or false value that is used to determine if the customer in the order form wishes to receive more information on the company's offers and promotions.

 bool DetailsDialog::sendOffers()
     return offersCheckBox->isChecked();

The verify() function is an additionally implemented slot used to verify the details entered by the user into the DetailsDialog. If the details entered are incomplete, a QMessageBox is displayed providing the user the option to discard the DetailsDialog. Otherwise, the details are accepted and the accept() function is invoked.

 void DetailsDialog::verify()
     if (!nameEdit->text().isEmpty() && !addressEdit->toPlainText().isEmpty()) {

     QMessageBox::StandardButton answer;
     answer = QMessageBox::warning(this, tr("Incomplete Form"),
         tr("The form does not contain all the necessary information.\n"
            "Do you want to discard it?"),
         QMessageBox::Yes | QMessageBox::No);

     if (answer == QMessageBox::Yes)

MainWindow Definition

The MainWindow class is a subclass of QMainWindow, implementing two slots - openDialog() and printFile(). It also contains a private instance of QTabWidget, letters.

 class MainWindow : public QMainWindow

     void createSample();

 public slots:
     void openDialog();
     void printFile();

     void createLetter(const QString &name, const QString &address,
                       QList<QPair<QString,int> > orderItems,
                       bool sendOffers);

     QAction *printAction;
     QTabWidget *letters;

MainWindow Implementation

The MainWindow constructor sets up the fileMenu and the required actions, newAction and printAction. These actions' triggered() signals are connected to the additionally implemented openDialog() slot and the default close() slot. The QTabWidget, letters, is instantiated and set as the window's central widget.

     QMenu *fileMenu = new QMenu(tr("&File"), this);
     QAction *newAction = fileMenu->addAction(tr("&New..."));
     printAction = fileMenu->addAction(tr("&Print..."), this, SLOT(printFile()));
     QAction *quitAction = fileMenu->addAction(tr("E&xit"));

     letters = new QTabWidget;

     connect(newAction, SIGNAL(triggered()), this, SLOT(openDialog()));
     connect(quitAction, SIGNAL(triggered()), this, SLOT(close()));

     setWindowTitle(tr("Order Form"));

The createLetter() function creates a new QTabWidget with a QTextEdit, editor, as the parent. This function accepts four parameters that correspond to we obtained through DetailsDialog, in order to "fill" the editor.

 void MainWindow::createLetter(const QString &name, const QString &address,
                               QList<QPair<QString,int> > orderItems,
                               bool sendOffers)
     QTextEdit *editor = new QTextEdit;
     int tabIndex = letters->addTab(editor, name);

We then obtain the cursor for the editor using QTextEdit::textCursor(). The cursor is then moved to the start of the document using QTextCursor::Start.

     QTextCursor cursor(editor->textCursor());

Recall the structure of a Rich Text Document, where sequences of frames and tables are always separated by text blocks, some of which may contain no information.

In the case of the Order Form Example, the document structure for this portion is described by the table below:

frame with referenceFrameFormat
blockA company
block321 City Street
blockIndustry Park
blockAnother country

This is accomplished with the following code:

     QTextFrame *topFrame = cursor.currentFrame();
     QTextFrameFormat topFrameFormat = topFrame->frameFormat();

     QTextCharFormat textFormat;
     QTextCharFormat boldFormat;

     QTextFrameFormat referenceFrameFormat;
     referenceFrameFormat.setWidth(QTextLength(QTextLength::PercentageLength, 40));

     cursor.insertText("A company", boldFormat);
     cursor.insertText("321 City Street");
     cursor.insertText("Industry Park");
     cursor.insertText("Another country");

Note that topFrame is the editor's top-level frame and is not shown in the document structure.

We then set the cursor's position back to its last position in topFrame and fill in the customer's name (provided by the constructor) and address - using a foreach loop to traverse the QString, address.


     cursor.insertText(name, textFormat);
     QString line;
     foreach (line, address.split("\n")) {

The cursor is now back in topFrame and the document structure for the above portion of code is:

block47338 Park Avenue
blockBig City

For spacing purposes, we invoke insertBlock() twice. The currentDate() is obtained and displayed. We use setWidth() to increase the width of bodyFrameFormat and we insert a new frame with that width.


     QDate date = QDate::currentDate();
     cursor.insertText(tr("Date: %1").arg(date.toString("d MMMM yyyy")),

     QTextFrameFormat bodyFrameFormat;
     bodyFrameFormat.setWidth(QTextLength(QTextLength::PercentageLength, 100));

The following code inserts standard text into the order form.

     cursor.insertText(tr("I would like to place an order for the following "
                          "items:"), textFormat);

This part of the document structure now contains the date, a frame with bodyFrameFormat, as well as the standard text.

blockDate: 25 May 2007
frame with bodyFrameFormat
blockI would like to place an order for the following items:

A QTextTableFormat object, orderTableFormat, is used to hold the type of item and the quantity ordered.

     QTextTableFormat orderTableFormat;
     QTextTable *orderTable = cursor.insertTable(1, 2, orderTableFormat);

     QTextFrameFormat orderFrameFormat = cursor.currentFrame()->frameFormat();

We use cellAt() to set the headers for the orderTable.

     cursor = orderTable->cellAt(0, 0).firstCursorPosition();
     cursor.insertText(tr("Product"), boldFormat);
     cursor = orderTable->cellAt(0, 1).firstCursorPosition();
     cursor.insertText(tr("Quantity"), boldFormat);

Then, we iterate through the QList of QPair objects to populate 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);

The resulting document structure for this section is:

orderTable with orderTableFormat
blockReference book
blockCoffee cup

The cursor is then moved back to topFrame's lastPosition() and more standard text is inserted.


     cursor.insertText(tr("Please update my records to take account of the "
                          "following privacy information:"));

Another QTextTable is inserted, to display the customer's preference regarding offers.

     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();
         cursor = offersTable->cellAt(1, 0).firstCursorPosition();

     cursor.insertText("X", boldFormat);

The document structure for this portion is:

blockPlease update my...
blockI want to receive...
blockI do not want to recieve...

The cursor is moved to insert "Sincerely" along with the customer's name. More blocks are inserted for spacing purposes. The printAction is enabled to indicate that an order form can now be printed.

     cursor.insertText(tr("Sincerely,"), textFormat);


The bottom portion of the document structure is:


The createSample() function is used for illustration purposes, to create a sample order form.

 void MainWindow::createSample()
     DetailsDialog dialog("Dialog with default values", this);
     createLetter("Mr. Smith", "12 High Street\nSmall Town\nThis country",
                  dialog.orderItems(), true);

The openDialog() function opens a DetailsDialog object. If the details in dialog are accepted, the createLetter() function is invoked using the parameters extracted from 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());

In order to print out the order form, a printFile() function is included, as shown below:

 void MainWindow::printFile()
 #ifndef QT_NO_PRINTER
     QTextEdit *editor = static_cast<QTextEdit*>(letters->currentWidget());
     QPrinter printer;

     QPrintDialog *dialog = new QPrintDialog(&printer, this);
     dialog->setWindowTitle(tr("Print Document"));
     if (editor->textCursor().hasSelection())
     if (dialog->exec() != QDialog::Accepted)


This function also allows the user to print a selected area with QTextCursor::hasSelection(), instead of printing the entire document.

main() Function

The main() function instantiates MainWindow and sets its size to 640x480 pixels before invoking the show() function and createSample() function.

 int main(int argc, char *argv[])
     QApplication app(argc, argv);
     MainWindow window;
     window.resize(640, 480);;
     return app.exec();

Best Of

Actualités les plus lues

  1. Microsoft ouvre aux autres compilateurs C++ AMP, la spécification pour la conception d'applications parallèles C++ utilisant le GPU 22
  2. Les développeurs ignorent-ils trop les failles découvertes dans leur code ? Prenez-vous en compte les remarques des autres ? 17
  3. RIM : « 13 % des développeurs ont gagné plus de 100 000 $ sur l'AppWord », Qt et open-source au menu du BlackBerry DevCon Europe 0
  4. BlackBerry 10 : premières images du prochain OS de RIM qui devrait intégrer des widgets et des tuiles inspirées de Windows Phone 0
  5. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 10
  6. Adieu qmake, bienvenue qbs : Qt Building Suite, un outil déclaratif et extensible pour la compilation de projets Qt 17
  7. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
Page suivante

Le Qt Labs au hasard


La folie est de mettre en forme le même texte

Les Qt Labs sont les laboratoires des développeurs de Qt, où ils peuvent partager des impressions sur le framework, son utilisation, ce que pourrait être son futur. Lire l'article.



Liens utiles


  • Vous souhaitez rejoindre la rédaction ou proposer un tutoriel, une traduction, une question... ? Postez dans le forum Contribuez ou contactez-nous par MP ou par email (voir en bas de page).

Qt dans le magazine

Cette page est une traduction d'une page de la documentation de Qt, écrite par Nokia Corporation and/or its subsidiary(-ies). Les éventuels problèmes résultant d'une mauvaise traduction ne sont pas imputables à Nokia. Qt 4.7
Copyright © 2012 Developpez LLC. Tous droits réservés Developpez LLC. Aucune reproduction, même partielle, ne peut être faite de ce site et de l'ensemble de son contenu : textes, documents et images sans l'autorisation expresse de Developpez LLC. Sinon, vous encourez selon la loi jusqu'à 3 ans de prison et jusqu'à 300 000 E de dommages et intérêts. Cette page est déposée à la SACD.
Vous avez déniché une erreur ? Un bug ? Une redirection cassée ? Ou tout autre problème, quel qu'il soit ? Ou bien vous désirez participer à ce projet de traduction ? N'hésitez pas à nous contacter ou par MP !

Hébergement Web