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  · 

Fridge Magnets Example

Files:

The Fridge Magnets example shows how to supply more than one type of MIME-encoded data with a drag and drop operation.

With this application the user can play around with a collection of fridge magnets, using drag and drop to form new sentences from the words on the magnets. The example consists of two classes:

  • DragLabel is a custom widget representing one single fridge magnet.
  • DragWidget provides the main application window.

We will first take a look at the DragWidget class, then we will take a quick look at the DragLabel class.

DragWidget Class Definition

The DragWidget class inherits QWidget, providing support for drag and drop operations:

 class DragWidget : public QWidget
 {
 public:
     DragWidget(QWidget *parent = 0);

 protected:
     void dragEnterEvent(QDragEnterEvent *event);
     void dragMoveEvent(QDragMoveEvent *event);
     void dropEvent(QDropEvent *event);
 };

To enable drag and drop, we simply reimplement the dragEnterEvent(), dragMoveEvent() and dropEvent() event handlers inherited from QWidget.

DragWidget Class Implementation

In the constructor, we first open the file containing the words on our fridge magnets:

 DragWidget::DragWidget(QWidget *parent)
     : QWidget(parent)
 {
     QFile dictionaryFile(":/dictionary/words.txt");
     dictionaryFile.open(QFile::ReadOnly);
     QTextStream inputStream(&dictionaryFile);

QFile is an I/O device for reading and writing text and binary files and resources, and may be used by itself or in combination with QTextStream or QDataStream. We have chosen to read the contents of the file using the QTextStream class that provides a convenient interface for reading and writing text.

     int x = 5;
     int y = 5;

     while (!inputStream.atEnd()) {
         QString word;
         inputStream >> word;
         if (!word.isEmpty()) {
             DragLabel *wordLabel = new DragLabel(word, this);
             wordLabel->move(x, y);
             wordLabel->show();
             x += wordLabel->width() + 2;
             if (x >= 245) {
                 x = 5;
                 y += wordLabel->height() + 2;
             }
         }
     }

Then we create the fridge magnets: As long as there is data (the QTextStream::atEnd() method returns true if there is no more data to be read from the stream), we read one line at a time using QTextStream's readLine() method. For each line, we create a DragLabel object using the read line as text, we calculate its position and ensure that it is visible by calling the QWidget::show() method.

     QPalette newPalette = palette();
     newPalette.setColor(QPalette::Window, Qt::white);
     setPalette(newPalette);

     setMinimumSize(400, qMax(200, y));
     setWindowTitle(tr("Fridge Magnets"));

We also set the FridgeMagnets widget's palette, minimum size and window title.

     setAcceptDrops(true);
 }

Finally, to enable our user to move the fridge magnets around, we must also set the FridgeMagnets widget's acceptDrops property. Setting this property to true announces to the system that this widget may be able to accept drop events (events that are sent when drag and drop actions are completed).

When a a drag and drop action enters our widget, we will receive a drag enter event. QDragEnterEvent inherits most of its functionality from QDragMoveEvent, which in turn inherits most of its functionality from QDropEvent. Note that we must accept this event in order to receive the drag move events that are sent while the drag and drop action is in progress. The drag enter event is always immediately followed by a drag move event.

In our dragEnterEvent() implementation, we first determine whether we support the event's MIME type or not:

 void DragWidget::dragEnterEvent(QDragEnterEvent *event)
 {
     if (event->mimeData()->hasFormat("application/x-fridgemagnet")) {
         if (children().contains(event->source())) {
             event->setDropAction(Qt::MoveAction);
             event->accept();
         } else {
             event->acceptProposedAction();
         }

If the type is "application/x-fridgemagnet" and the event origins from any of this application's fridge magnet widgets, we first set the event's drop action using the QDropEvent::setDropAction() method. An event's drop action is the action to be performed on the data by the target. Qt::MoveAction indicates that the data is moved from the source to the target.

Then we call the event's accept() method to indicate that we have handled the event. In general, unaccepted events might be propagated to the parent widget. If the event origins from any other widget, we simply accept the proposed action.

     } else if (event->mimeData()->hasText()) {
         event->acceptProposedAction();
     } else {
         event->ignore();
     }
 }

We also accept the proposed action if the event's MIME type is text/plain, i.e., if QMimeData::hasText() returns true. If the event has any other type, on the other hand, we call the event's ignore() method allowing the event to be propagated further.

 void DragWidget::dragMoveEvent(QDragMoveEvent *event)
 {
     if (event->mimeData()->hasFormat("application/x-fridgemagnet")) {
         if (children().contains(event->source())) {
             event->setDropAction(Qt::MoveAction);
             event->accept();
         } else {
             event->acceptProposedAction();
         }
     } else if (event->mimeData()->hasText()) {
         event->acceptProposedAction();
     } else {
         event->ignore();
     }
 }

Drag move events occur when the cursor enters a widget, when it moves within the widget, and when a modifier key is pressed on the keyboard while the widget has focus. Our widget will receive drag move events repeatedly while a drag is within its boundaries. We reimplement the dragMoveEvent() method, and examine the event in the exact same way as we did with drag enter events.

 void DragWidget::dropEvent(QDropEvent *event)
 {
     if (event->mimeData()->hasFormat("application/x-fridgemagnet")) {
         const QMimeData *mime = event->mimeData();

Note that the dropEvent() event handler behaves slightly different: We first get hold of the event's MIME data. The QMimeData class provides a container for data that records information about its MIME type. QMimeData objects associate the data that they hold with the corresponding MIME types to ensure that information can be safely transferred between applications, and copied around within the same application.

         QByteArray itemData = mime->data("application/x-fridgemagnet");
         QDataStream dataStream(&itemData, QIODevice::ReadOnly);

         QString text;
         QPoint offset;
         dataStream >> text >> offset;

         DragLabel *newLabel = new DragLabel(text, this);
         newLabel->move(event->pos() - offset);
         newLabel->show();

         if (children().contains(event->source())) {
             event->setDropAction(Qt::MoveAction);
             event->accept();
         } else {
             event->acceptProposedAction();
         }

Then we retrieve the data associated with the "application/x-fridgemagnet" MIME type using a data stream, and create a new DragLabel object. The QDataStream class provides serialization of binary data to a QIODevice (a data stream is a binary stream of encoded information which is 100% independent of the host computer's operating system, CPU or byte order).

Finally, we move the magnet to the event's position before we check if the event origins from any of this application's fridge magnet widgets. If it does, we set the event's drop action to Qt::MoveAction and call the event's accept() method. Otherwise, we simply accept the proposed action.

     } else if (event->mimeData()->hasText()) {
         QStringList pieces = event->mimeData()->text().split(QRegExp("\\s+"),
                              QString::SkipEmptyParts);
         QPoint position = event->pos();

         foreach (QString piece, pieces) {
             DragLabel *newLabel = new DragLabel(piece, this);
             newLabel->move(position);
             newLabel->show();

             position += QPoint(newLabel->width(), 0);
         }

         event->acceptProposedAction();
     } else {
         event->ignore();
     }
 }

If the event's MIME type is text/plain, i.e., if QMimeData::hasText() returns true, we retrieve its text and split it into words. For each word we create a new DragLabel action, and show it at the event's position plus an offset depending on the number of words in the text. In the end we accept the proposed action.

If the event has any other type, we call the event's ignore() method allowing the event to be propagated further.

This completes the DragWidget implementation. Now, let's take a quick look at the DragLabel class.

DragLabel Class Definition

Each fridge magnet is represented by an instance of the DragLabel class:

 class DragLabel : public QLabel
 {
 public:
     DragLabel(const QString &text, QWidget *parent);

 protected:
     void mousePressEvent(QMouseEvent *event);

 private:
     QString labelText;
 };

Earlier we set our main application widget's acceptDrops property and reimplemented QWidget's dragEnterEvent(), dragMoveEvent() and dropEvent() event handlers to support drag and drop. In addition, we must reimplement the mousePressEvent() method in our fridge magnet widget to make the user able to pick it up in the first place.

DragLabel Class Implementation

In the DragLabel constructor, we first create a QImage object on which we will draw the fridge magnet's text and frame:

 DragLabel::DragLabel(const QString &text, QWidget *parent)
     : QLabel(parent)
 {
     QFontMetrics metric(font());
     QSize size = metric.size(Qt::TextSingleLine, text);

     QImage image(size.width() + 12, size.height() + 12,
                  QImage::Format_ARGB32_Premultiplied);
     image.fill(qRgba(0, 0, 0, 0));

     QFont font;
     font.setStyleStrategy(QFont::ForceOutline);

Its size depends on the current font size, and its format is QImage::Format_ARGB32_Premultiplied (i.e., the image is stored using a premultiplied 32-bit ARGB format (0xAARRGGBB)).

Then we constructs a font object that uses the application's default font, and set its style strategy. The style strategy tells the font matching algorithm what type of fonts should be used to find an appropriate default family. The QFont::ForceOutline forces the use of outline fonts.

     QPainter painter;
     painter.begin(&image);
     painter.setRenderHint(QPainter::Antialiasing);
     painter.setBrush(Qt::white);
     painter.drawRoundedRect(QRectF(0.5, 0.5, image.width()-1, image.height()-1),
                             25, 25, Qt::RelativeSize);

     painter.setFont(font);
     painter.setBrush(Qt::black);
     painter.drawText(QRect(QPoint(6, 6), size), Qt::AlignCenter, text);
     painter.end();

To draw the text and frame onto the image, we use the QPainter class. QPainter provides highly optimized methods to do most of the drawing GUI programs require. It can draw everything from simple lines to complex shapes like pies and chords. It can also draw aligned text and pixmaps.

A painter can be activated by passing a paint device to the constructor, or by using the begin() method as we do in this example. The end() method deactivates it. Note that the latter function is called automatically upon destruction when the painter is actived by its constructor. The QPainter::Antialiasing render hint ensures that the paint engine will antialias the edges of primitives if possible.

     setPixmap(QPixmap::fromImage(image));
     labelText = text;
 }

When the painting is done, we convert our image to a pixmap using QPixmap's fromImage() method. This method also takes an optional flags argument, and converts the given image to a pixmap using the specified flags to control the conversion (the flags argument is a bitwise-OR of the Qt::ImageConversionFlags; passing 0 for flags sets all the default options).

Finally, we set the label's pixmap property and store the label's text for later use. Note that setting the pixmap clears any previous content, and disables the label widget's buddy shortcut, if any.

Now, let's take a look at the mousePressEvent() event handler:

 void DragLabel::mousePressEvent(QMouseEvent *event)
     QByteArray itemData;
     QDataStream dataStream(&itemData, QIODevice::WriteOnly);
     dataStream << labelText << QPoint(event->pos() - rect().topLeft());

Mouse events occur when a mouse button is pressed or released inside a widget, or when the mouse cursor is moved. By reimplementing the mousePressEvent() method we ensure that we will receive mouse press events for the fridge magnet widget.

Whenever we receive such an event, we will first create a byte array to store our item data, and a QDataStream object to stream the data to the byte array.

     QMimeData *mimeData = new QMimeData;
     mimeData->setData("application/x-fridgemagnet", itemData);
     mimeData->setText(labelText);

Then we create a new QMimeData object. As mentioned above, QMimeData objects associate the data that they hold with the corresponding MIME types to ensure that information can be safely transferred between applications. The setData() method sets the data associated with a given MIME type. In our case, we associate our item data with the custom "application/x-fridgemagnet" type.

Note that we also associate the magnet's text with the text/plain MIME type using QMimeData's setText() method. We have already seen how our main widget detects both these MIME types with its event handlers.

     QDrag *drag = new QDrag(this);
     drag->setMimeData(mimeData);
     drag->setHotSpot(event->pos() - rect().topLeft());
     drag->setPixmap(*pixmap());

     hide();

Finally, we create a QDrag object. It is the QDrag class that handles most of the details of a drag and drop operation, providing support for MIME-based drag and drop data transfer. The data to be transferred by the drag and drop operation is contained in a QMimeData object. When we call QDrag's setMimeData() method the ownership of our item data is transferred to the QDrag object.

We also specify the cursor's hot spot, i.e., its position while the drag is in progress, to be the top-left corner of our fridge magnet. We call the setPixmap() method to set the pixmap used to represent the data during the drag and drop operation. Typically, this pixmap shows an icon that represents the MIME type of the data being transferred, but any pixmap can be used. In this example, we have chosen to use the fridge magnet image itself to make the magnet appear as moving, immediately hiding the activated widget.

     if (drag->exec(Qt::MoveAction | Qt::CopyAction, Qt::CopyAction) == Qt::MoveAction)
         close();
     else
         show();
 }

Then we start the drag using QDrag's exec() method requesting that the magnet is moved when the drag is completed. The method returns the performed drop action; if this action is equal to Qt::MoveAction we will close the activated fridge magnet widget because we then create a new one (with the same data) at the drop position (see the implementation of our main widgets dropEvent() method). Otherwise, if the drop is outside our main widget, we simply show the widget in its original position.

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 94
  2. Apercevoir la troisième dimension ou l'utilisation multithreadée d'OpenGL dans Qt, un article des Qt Quarterly traduit par Guillaume Belz 0
  3. Les développeurs ignorent-ils trop les failles découvertes dans leur code ? Prenez-vous en compte les remarques des autres ? 17
  4. Pourquoi les programmeurs sont-ils moins payés que les gestionnaires de programmes ? Manquent-ils de pouvoir de négociation ? 42
  5. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
  6. 2017 : un quinquennat pour une nouvelle version du C++ ? Possible, selon Herb Sutter 9
  7. Qt Commercial : Digia organise un webinar gratuit le 27 mars sur la conception d'interfaces utilisateur et d'applications avec le framework 0
Page suivante

Le blog Digia au hasard

Logo

Une nouvelle ère d'IHM 3D pour les automobiles

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 qtextended4.4
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