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  ·  Tous les espaces de nom  ·  Toutes les classes  ·  Classes principales  ·  Annotées  ·  Classes groupées  ·  Modules  ·  Fonctions  · 

Porting to Qt 4 - Drag and Drop

Qt 4 introduces a new set of classes to handle drag and drop operations that aim to be easier to use than their counterparts in Qt 3. As a result, the way that drag and drop is performed is quite different to the way developers of Qt 3 applications have come to expect. In this guide, we show the differences between the old and new APIs and indicate where applications need to be changed when they are ported to Qt 4.

Dragging

In Qt 3, drag operations are encapsulated by QDragObject (see Q3DragObject) and its subclasses. These objects are typically constructed on the heap in response to mouse click or mouse move events, and ownership of them is transferred to Qt so that they can be deleted when the corresponding drag and drop operations have been completed. The drag source has no control over how the drag and drop operation is performed once the object's drag() function is called, and it receives no information about how the operation ended.

 void MyQt3Widget::customStartDragFunction()
 {
     QDragObject *d = new QTextDrag( myHighlightedText(), this );
     d->dragCopy();
     // do NOT delete d.
 }

Similarly, in Qt 4, drag operations are also initiated when a QDrag object is constructed and its exec() function is called. In contrast, these objects are typically constructed on the stack rather than the heap since each drag and drop operation is performed synchronously as far as the drag source is concerned. One key benefit of this is that the drag source can receive information about how the operation ended from the value returned by exec().

 void MyWidget::mousePressEvent(QMouseEvent *event)
 {
     if (event->button() == Qt::LeftButton) {

         QDrag *drag = new QDrag(this);
         QMimeData *mimeData = new QMimeData;

         mimeData->setText(text);
         mimeData->setImageData(image);
         drag->setMimeData(mimeData);
         drag->setPixmap(iconPixmap);

         Qt::DropAction dropAction = drag->exec();
         ...
         event->accept();
     }
 }

A key difference in the above code is the use of the QMimeData class to hold information about the data that is transferred. Qt 3 relies on subclasses of QDragObject to provide support for specific MIME types; in Qt 4, the use of QMimeData as a generic container for data makes the relationship between MIME type and data more tranparent. QMimeData is described in more detail later in this document.

Dropping

In both Qt 3 and Qt 4, it is possible to prepare a custom widget to accept dropped data by enabling the acceptDrops property of a widget, usually in the widget's constructor. As a result, the widget will receive drag enter events that can be handled by its dragEnterEvent() function. As in Qt 3, custom widgets in Qt 4 handle these events by determining whether the data supplied by the drag and drop operation can be dropped onto the widget. Since the classes used to encapsulate MIME data are different in Qt 3 and Qt 4, the exact implementations differ.

In Qt 3, the drag enter event is handled by checking whether each of the standard QDragObject subclasses can decode the data supplied, and indicating success or failure of these checks via the event's accept() function, as shown in this simple example:

 void MyQt3Widget::dragEnterEvent(QDragEnterEvent* event)
 {
     event->accept(
         QTextDrag::canDecode(event) ||
         QImageDrag::canDecode(event)
     );
 }

In Qt 4, you can examine the MIME type describing the data to determine whether the widget should accept the event or, for common data types, you can use convenience functions:

 void MyWidget::dragEnterEvent(QDragEnterEvent *event)
 {
     if (event->mimeData()->hasText() || event->mimeData()->hasImage())
         event->acceptProposedAction();
 }

The widget has some control over the type of drag and drop operation to be performed. In the above code, the action proposed by the drag source is accepted, but this can be overridden if required.

In both Qt 3 and Qt 4, it is necessary to accept a given drag event in order to receive the corresponding drop event. A custom widget in Qt 3 that can accept dropped data in the form of text or images might provide an implementation of dropEvent() that looks like the following:

 void MyQt3Widget::dropEvent(QDropEvent* event)
 {
     QImage image;
     QString text;

     if ( QImageDrag::decode(event, image) ) {
         insertImageAt(image, event->pos());
     } else if ( QTextDrag::decode(event, text) ) {
         insertTextAt(text, event->pos());
     }
 }

In Qt 4, the event is handled in a similar way:

 void MyWidget::dropEvent(QDropEvent *event)
 {
     if (event->mimeData()->hasText())
         dataLabel->setText(event->mimeData()->text());
     else if (event->mimeData()->hasImage()) {
         QVariant imageData = event->mimeData()->imageData();
         dataLabel->setPixmap(qvariant_cast<QPixmap>(imageData));
     }
     event->acceptProposedAction();
 }

It is also possible to extract data stored for a particular MIME type if it was specified by the drag source.

MIME Types and Data

In Qt 3, data to be transferred in drag and drop operations is encapsulated in instances of QDragObject and its subclasses, representing specific data formats related to common MIME type and subtypes.

In Qt 4, only the QMimeData class is used to represent data, providing a container for data stored in multiple formats, each associated with a relevant MIME type. Since arbitrary MIME types can be specified, there is no need for an extensive class hierarchy to represent different kinds of information. Additionally, QMimeData it provides some convenience functions to allow the most common data formats to be stored and retrieved with less effort than for arbitrary MIME types.

[Previous: Porting to Qt 4 - Virtual Functions] [Contents] [Next: Porting .ui Files to Qt 4]

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. Adieu qmake, bienvenue qbs : Qt Building Suite, un outil déclaratif et extensible pour la compilation de projets Qt 17
  7. 2017 : un quinquennat pour une nouvelle version du C++ ? Possible, selon Herb Sutter 8
Page suivante

Le Qt Quarterly au hasard

Logo

Se brancher au Web

Qt Quarterly est la revue trimestrielle proposée par Nokia et à destination des développeurs Qt. Ces articles d'une grande qualité technique sont rédigés par des experts Qt. 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.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