Viadeo Twitter Google Bookmarks ! Facebook Digg del.icio.us 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  · 

Spin Box Delegate Example

Files:

The Spin Box Delegate example shows how to create an editor for a custom delegate in the model/view framework by reusing a standard Qt editor widget.

The model/view framework provides a standard delegate that is used by default with the standard view classes. For most purposes, the selection of editor widgets available through this delegate is sufficient for editing text, boolean values, and other simple data types. However, for specific data types, it is sometimes necessary to use a custom delegate to either display the data in a specific way, or allow the user to edit it with a custom control.

This concepts behind this example are covered in the Delegate Classes chapter of the Model/View Programming overview.

SpinBoxDelegate Class Definition

The definition of the delegate is as follows:

 class SpinBoxDelegate : public QItemDelegate
 {
     Q_OBJECT

 public:
     SpinBoxDelegate(QObject *parent = 0);

     QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,
                           const QModelIndex &index) const;

     void setEditorData(QWidget *editor, const QModelIndex &index) const;
     void setModelData(QWidget *editor, QAbstractItemModel *model,
                       const QModelIndex &index) const;

     void updateEditorGeometry(QWidget *editor,
         const QStyleOptionViewItem &option, const QModelIndex &index) const;
 };

The delegate class declares only those functions that are needed to create an editor widget, display it at the correct location in a view, and communicate with a model. Custom delegates can also provide their own painting code by reimplementing the paintEvent() function.

SpinBoxDelegate Class Implementation

Since the delegate is stateless, the constructor only needs to call the base class's constructor with the parent QObject as its argument:

 SpinBoxDelegate::SpinBoxDelegate(QObject *parent)
     : QItemDelegate(parent)
 {
 }

Since the delegate is a subclass of QItemDelegate, the data it retrieves from the model is displayed in a default style, and we do not need to provide a custom paintEvent().

The createEditor() function returns an editor widget, in this case a spin box that restricts values from the model to integers from 0 to 100 inclusive.

 QWidget *SpinBoxDelegate::createEditor(QWidget *parent,
     const QStyleOptionViewItem &/* option */,
     const QModelIndex &/* index */) const
 {
     QSpinBox *editor = new QSpinBox(parent);
     editor->setMinimum(0);
     editor->setMaximum(100);

     return editor;
 }

We install an event filter on the spin box to ensure that it behaves in a way that is consistent with other delegates. The implementation for the event filter is provided by the base class.

The setEditorData() function reads data from the model, converts it to an integer value, and writes it to the editor widget.

 void SpinBoxDelegate::setEditorData(QWidget *editor,
                                     const QModelIndex &index) const
 {
     int value = index.model()->data(index, Qt::EditRole).toInt();

     QSpinBox *spinBox = static_cast<QSpinBox*>(editor);
     spinBox->setValue(value);
 }

Since the view treats delegates as ordinary QWidget instances, we have to use a static cast before we can set the value in the spin box.

The setModelData() function reads the contents of the spin box, and writes it to the model.

 void SpinBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
                                    const QModelIndex &index) const
 {
     QSpinBox *spinBox = static_cast<QSpinBox*>(editor);
     spinBox->interpretText();
     int value = spinBox->value();

     model->setData(index, value, Qt::EditRole);
 }

We call interpretText() to make sure that we obtain the most up-to-date value in the spin box.

The updateEditorGeometry() function updates the editor widget's geometry using the information supplied in the style option. This is the minimum that the delegate must do in this case.

 void SpinBoxDelegate::updateEditorGeometry(QWidget *editor,
     const QStyleOptionViewItem &option, const QModelIndex &/* index */) const
 {
     editor->setGeometry(option.rect);
 }

More complex editor widgets may divide the rectangle available in option.rect between different child widgets if required.

The Main Function

This example is written in a slightly different way to many of the other examples supplied with Qt. To demonstrate the use of a custom editor widget in a standard view, it is necessary to set up a model containing some arbitrary data and a view to display it.

We set up the application in the normal way, construct a standard item model to hold some data, set up a table view to use the data in the model, and construct a custom delegate to use for editing:

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

     QStandardItemModel model(4, 2);
     QTableView tableView;
     tableView.setModel(&model);

     SpinBoxDelegate delegate;
     tableView.setItemDelegate(&delegate);

The table view is informed about the delegate, and will use it to display each of the items. Since the delegate is a subclass of QItemDelegate, each cell in the table will be rendered using standard painting operations.

We insert some arbitrary data into the model for demonstration purposes:

     for (int row = 0; row < 4; ++row) {
         for (int column = 0; column < 2; ++column) {
             QModelIndex index = model.index(row, column, QModelIndex());
             model.setData(index, QVariant((row+1) * (column+1)));
         }
     }

Finally, the table view is displayed with a window title, and we start the application's event loop:

     tableView.setWindowTitle(QObject::tr("Spin Box Delegate"));
     tableView.show();
     return app.exec();
 }

Each of the cells in the table can now be edited in the usual way, but the spin box ensures that the data returned to the model is always constrained by the values allowed by the spin box delegate.

Publicité

Best Of

Actualités les plus lues

Semaine
Mois
Année
  1. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 103
  2. Pourquoi les programmeurs sont-ils moins payés que les gestionnaires de programmes ? Manquent-ils de pouvoir de négociation ? 56
  3. «Le projet de loi des droits du développeur» : quelles conditions doivent remplir les entreprises pour que le développeur puisse réussir ? 93
  4. Les développeurs détestent-ils les antivirus ? Un programmeur manifeste sa haine envers ces solutions de sécurité 32
  5. Qt Commercial : Digia organise un webinar gratuit le 27 mars sur la conception d'interfaces utilisateur et d'applications avec le framework 0
  6. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
  7. 2017 : un quinquennat pour une nouvelle version du C++ ? Possible, selon Herb Sutter 11
Page suivante
  1. Linus Torvalds : le "C++ est un langage horrible", en justifiant le choix du C pour le système de gestion de version Git 100
  2. Comment prendre en compte l'utilisateur dans vos applications ? Pour un développeur, « 90 % des utilisateurs sont des idiots » 231
  3. Quel est LE livre que tout développeur doit lire absolument ? Celui qui vous a le plus marqué et inspiré 96
  4. Apple cède et s'engage à payer des droits à Nokia, le conflit des brevets entre les deux firmes s'achève 158
  5. Nokia porte à nouveau plainte contre Apple pour violation de sept nouveaux brevets 158
  6. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 103
  7. Quel est le code dont vous êtes le plus fier ? Pourquoi l'avez-vous écrit ? Et pourquoi vous a-t-il donné autant de satisfaction ? 83
Page suivante

Le blog Digia au hasard

Logo

Créer des applications avec un style Metro avec Qt, exemples en QML et C++, un article de Digia Qt traduit par Thibaut Cuvelier

Le blog Digia est l'endroit privilégié pour la communication sur l'édition commerciale de Qt, où des réponses publiques sont apportées aux questions les plus posées au support. Lire l'article.

Communauté

Ressources

Liens utiles

Contact

  • 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.5
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 !
 
 
 
 
Partenaires

Hébergement Web