Sophie

Sophie

distrib > Mageia > 6 > armv5tl > media > core-updates > by-pkgid > 768f7d9f703884aa2562bf0a651086df > files > 3790

qtbase5-doc-5.9.4-1.1.mga6.noarch.rpm

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- fridgemagnets.qdoc -->
  <title>Fridge Magnets Example | Qt Widgets 5.9</title>
  <link rel="stylesheet" type="text/css" href="style/offline-simple.css" />
  <script type="text/javascript">
    document.getElementsByTagName("link").item(0).setAttribute("href", "style/offline.css");
    // loading style sheet breaks anchors that were jumped to before
    // so force jumping to anchor again
    setTimeout(function() {
        var anchor = location.hash;
        // need to jump to different anchor first (e.g. none)
        location.hash = "#";
        setTimeout(function() {
            location.hash = anchor;
        }, 0);
    }, 0);
  </script>
</head>
<body>
<div class="header" id="qtdocheader">
  <div class="main">
    <div class="main-rounded">
      <div class="navigationbar">
        <table><tr>
<td >Qt 5.9</td><td ><a href="qtwidgets-index.html">Qt Widgets</a></td><td >Fridge Magnets Example</td></tr></table><table class="buildversion"><tr>
<td id="buildversion" width="100%" align="right">Qt 5.9.4 Reference Documentation</td>
        </tr></table>
      </div>
    </div>
<div class="content">
<div class="line">
<div class="content mainContent">
<div class="sidebar">
<div class="toc">
<h3><a name="toc">Contents</a></h3>
<ul>
<li class="level1"><a href="#draglabel-class-definition">DragLabel Class Definition</a></li>
<li class="level1"><a href="#draglabel-class-implementation">DragLabel Class Implementation</a></li>
<li class="level1"><a href="#dragwidget-class-definition">DragWidget Class Definition</a></li>
<li class="level1"><a href="#dragwidget-class-implementation">DragWidget Class Implementation</a></li>
<li class="level2"><a href="#dragging">Dragging</a></li>
<li class="level2"><a href="#dropping">Dropping</a></li>
<li class="level1"><a href="#summary">Summary</a></li>
</ul>
</div>
<div class="sidebar-content" id="sidebar-content"></div></div>
<h1 class="title">Fridge Magnets Example</h1>
<span class="subtitle"></span>
<!-- $$$draganddrop/fridgemagnets-description -->
<div class="descr"> <a name="details"></a>
<p>The Fridge Magnets example shows how to supply more than one type of MIME-encoded data with a drag and drop operation.</p>
<p class="centerAlign"><img src="images/fridgemagnets-example.png" alt="" /></p><p>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:</p>
<ul>
<li><code>DragLabel</code> is a custom widget representing one single fridge magnet.</li>
<li><code>DragWidget</code> provides the main application window.</li>
</ul>
<p>We will first take a look at the <code>DragLabel</code> class, then we will examine the <code>DragWidget</code> class.</p>
<a name="draglabel-class-definition"></a>
<h2 id="draglabel-class-definition">DragLabel Class Definition</h2>
<p>Each fridge magnet is represented by an instance of the <code>DragLabel</code> class:</p>
<pre class="cpp">

  <span class="keyword">class</span> DragLabel : <span class="keyword">public</span> <span class="type"><a href="qlabel.html">QLabel</a></span>
  {
  <span class="keyword">public</span>:
      DragLabel(<span class="keyword">const</span> <span class="type"><a href="../qtcore/qstring.html">QString</a></span> <span class="operator">&amp;</span>text<span class="operator">,</span> <span class="type"><a href="qwidget.html">QWidget</a></span> <span class="operator">*</span>parent);
      <span class="type"><a href="../qtcore/qstring.html">QString</a></span> labelText() <span class="keyword">const</span>;

  <span class="keyword">private</span>:
      <span class="type"><a href="../qtcore/qstring.html">QString</a></span> m_labelText;
  };

</pre>
<p>Each instance of this <a href="qlabel.html">QLabel</a> subclass will be used to display an pixmap generated from a text string. Since we cannot store both text and a pixmap in a standard label, we declare a private variable to hold the original text, and we define an additional member function to allow it to be accessed.</p>
<a name="draglabel-class-implementation"></a>
<h2 id="draglabel-class-implementation">DragLabel Class Implementation</h2>
<p>In the <code>DragLabel</code> constructor, we first create a <a href="../qtgui/qimage.html">QImage</a> object on which we will draw the fridge magnet's text and frame:</p>
<pre class="cpp">

  DragLabel<span class="operator">::</span>DragLabel(<span class="keyword">const</span> <span class="type"><a href="../qtcore/qstring.html">QString</a></span> <span class="operator">&amp;</span>text<span class="operator">,</span> <span class="type"><a href="qwidget.html">QWidget</a></span> <span class="operator">*</span>parent)
      : <span class="type"><a href="qlabel.html">QLabel</a></span>(parent)
  {
      <span class="type"><a href="../qtgui/qfontmetrics.html">QFontMetrics</a></span> metric(font());
      <span class="type"><a href="../qtcore/qsize.html">QSize</a></span> size <span class="operator">=</span> metric<span class="operator">.</span>size(<span class="type"><a href="../qtcore/qt.html">Qt</a></span><span class="operator">::</span>TextSingleLine<span class="operator">,</span> text);

      <span class="type"><a href="../qtgui/qimage.html">QImage</a></span> image(size<span class="operator">.</span>width() <span class="operator">+</span> <span class="number">12</span><span class="operator">,</span> size<span class="operator">.</span>height() <span class="operator">+</span> <span class="number">12</span><span class="operator">,</span> <span class="type"><a href="../qtgui/qimage.html">QImage</a></span><span class="operator">::</span>Format_ARGB32_Premultiplied);
      image<span class="operator">.</span>fill(<a href="../qtgui/qcolor.html#qRgba">qRgba</a>(<span class="number">0</span><span class="operator">,</span> <span class="number">0</span><span class="operator">,</span> <span class="number">0</span><span class="operator">,</span> <span class="number">0</span>));

      <span class="type"><a href="../qtgui/qfont.html">QFont</a></span> font;
      font<span class="operator">.</span>setStyleStrategy(<span class="type"><a href="../qtgui/qfont.html">QFont</a></span><span class="operator">::</span>ForceOutline);

</pre>
<p>Its size depends on the current font size, and its format is <a href="../qtgui/qimage.html#Format-enum">QImage::Format_ARGB32_Premultiplied</a>; i.e&#x2e;, the image is stored using a premultiplied 32-bit ARGB format (0xAARRGGBB).</p>
<p>We then construct 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 <a href="../qtgui/qfont.html#StyleStrategy-enum">QFont::ForceOutline</a> forces the use of outline fonts.</p>
<p>To draw the text and frame onto the image, we use the <a href="../qtgui/qpainter.html">QPainter</a> class. <a href="../qtgui/qpainter.html">QPainter</a> 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.</p>
<pre class="cpp">

      <span class="type"><a href="../qtgui/qlineargradient.html">QLinearGradient</a></span> gradient(<span class="number">0</span><span class="operator">,</span> <span class="number">0</span><span class="operator">,</span> <span class="number">0</span><span class="operator">,</span> image<span class="operator">.</span>height()<span class="operator">-</span><span class="number">1</span>);
      gradient<span class="operator">.</span>setColorAt(<span class="number">0.0</span><span class="operator">,</span> <span class="type"><a href="../qtcore/qt.html">Qt</a></span><span class="operator">::</span>white);
      gradient<span class="operator">.</span>setColorAt(<span class="number">0.2</span><span class="operator">,</span> <span class="type"><a href="../qtgui/qcolor.html">QColor</a></span>(<span class="number">200</span><span class="operator">,</span> <span class="number">200</span><span class="operator">,</span> <span class="number">255</span>));
      gradient<span class="operator">.</span>setColorAt(<span class="number">0.8</span><span class="operator">,</span> <span class="type"><a href="../qtgui/qcolor.html">QColor</a></span>(<span class="number">200</span><span class="operator">,</span> <span class="number">200</span><span class="operator">,</span> <span class="number">255</span>));
      gradient<span class="operator">.</span>setColorAt(<span class="number">1.0</span><span class="operator">,</span> <span class="type"><a href="../qtgui/qcolor.html">QColor</a></span>(<span class="number">127</span><span class="operator">,</span> <span class="number">127</span><span class="operator">,</span> <span class="number">200</span>));

      <span class="type"><a href="../qtgui/qpainter.html">QPainter</a></span> painter;
      painter<span class="operator">.</span>begin(<span class="operator">&amp;</span>image);
      painter<span class="operator">.</span>setRenderHint(<span class="type"><a href="../qtgui/qpainter.html">QPainter</a></span><span class="operator">::</span>Antialiasing);
      painter<span class="operator">.</span>setBrush(gradient);
      painter<span class="operator">.</span>drawRoundedRect(<span class="type"><a href="../qtcore/qrectf.html">QRectF</a></span>(<span class="number">0.5</span><span class="operator">,</span> <span class="number">0.5</span><span class="operator">,</span> image<span class="operator">.</span>width()<span class="operator">-</span><span class="number">1</span><span class="operator">,</span> image<span class="operator">.</span>height()<span class="operator">-</span><span class="number">1</span>)<span class="operator">,</span>
                              <span class="number">25</span><span class="operator">,</span> <span class="number">25</span><span class="operator">,</span> <span class="type"><a href="../qtcore/qt.html">Qt</a></span><span class="operator">::</span>RelativeSize);

      painter<span class="operator">.</span>setFont(font);
      painter<span class="operator">.</span>setBrush(<span class="type"><a href="../qtcore/qt.html">Qt</a></span><span class="operator">::</span>black);
      painter<span class="operator">.</span>drawText(<span class="type"><a href="../qtcore/qrect.html">QRect</a></span>(<span class="type"><a href="../qtcore/qpoint.html">QPoint</a></span>(<span class="number">6</span><span class="operator">,</span> <span class="number">6</span>)<span class="operator">,</span> size)<span class="operator">,</span> <span class="type"><a href="../qtcore/qt.html">Qt</a></span><span class="operator">::</span>AlignCenter<span class="operator">,</span> text);
      painter<span class="operator">.</span>end();

</pre>
<p>A painter can be activated by passing a paint device to the constructor, or by using the <a href="../qtgui/qpainter.html#begin">begin()</a> method as we do in this example. The <a href="../qtgui/qpainter.html#end">end()</a> method deactivates it. Note that the latter function is called automatically upon destruction when the painter is actived by its constructor. The <a href="../qtgui/qpainter.html#RenderHint-enum">QPainter::Antialiasing</a> render hint ensures that the paint engine will antialias the edges of primitives if possible.</p>
<p>When the painting is done, we convert our image to a pixmap using <a href="../qtgui/qpixmap.html">QPixmap</a>'s <a href="../qtgui/qpixmap.html#fromImage">fromImage()</a> 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 <a href="../qtcore/qt.html#ImageConversionFlag-enum">Qt::ImageConversionFlags</a>; passing 0 for flags sets all the default options).</p>
<pre class="cpp">

      setPixmap(<span class="type"><a href="../qtgui/qpixmap.html">QPixmap</a></span><span class="operator">::</span>fromImage(image));
      m_labelText <span class="operator">=</span> text;
  }

</pre>
<p>Finally, we set the label's <a href="qlabel.html#pixmap-prop">pixmap property</a> and store the label's text for later use.</p>
<p><i>Note that setting the pixmap clears any previous content, including any text previously set using <a href="qlabel.html#text-prop">QLabel::setText</a>(), and disables the label widget's buddy shortcut, if any.</i></p>
<a name="dragwidget-class-definition"></a>
<h2 id="dragwidget-class-definition">DragWidget Class Definition</h2>
<p>The <code>DragWidget</code> class inherits <a href="qwidget.html">QWidget</a>, providing support for drag and drop operations:</p>
<pre class="cpp">

  <span class="keyword">class</span> DragWidget : <span class="keyword">public</span> <span class="type"><a href="qwidget.html">QWidget</a></span>
  {
  <span class="keyword">public</span>:
      DragWidget(<span class="type"><a href="qwidget.html">QWidget</a></span> <span class="operator">*</span>parent <span class="operator">=</span> <span class="number">0</span>);

  <span class="keyword">protected</span>:
      <span class="type">void</span> dragEnterEvent(<span class="type"><a href="../qtgui/qdragenterevent.html">QDragEnterEvent</a></span> <span class="operator">*</span>event) override;
      <span class="type">void</span> dragMoveEvent(<span class="type"><a href="../qtgui/qdragmoveevent.html">QDragMoveEvent</a></span> <span class="operator">*</span>event) override;
      <span class="type">void</span> dropEvent(<span class="type"><a href="../qtgui/qdropevent.html">QDropEvent</a></span> <span class="operator">*</span>event) override;
      <span class="type">void</span> mousePressEvent(<span class="type"><a href="../qtgui/qmouseevent.html">QMouseEvent</a></span> <span class="operator">*</span>event) override;
  };

</pre>
<p>To make the widget responsive to drag and drop operations, we simply reimplement the <a href="qwidget.html#dragEnterEvent">dragEnterEvent()</a>, <a href="qwidget.html#dragMoveEvent">dragMoveEvent()</a> and <a href="qwidget.html#dropEvent">dropEvent()</a> event handlers inherited from <a href="qwidget.html">QWidget</a>.</p>
<p>We also reimplement <a href="qwidget.html#mousePressEvent">mousePressEvent()</a> to make the widget responsive to mouse clicks. This is where we will write code to start drag and drop operations.</p>
<a name="dragwidget-class-implementation"></a>
<h2 id="dragwidget-class-implementation">DragWidget Class Implementation</h2>
<p>In the constructor, we first open the file containing the words on our fridge magnets:</p>
<pre class="cpp">

  DragWidget<span class="operator">::</span>DragWidget(<span class="type"><a href="qwidget.html">QWidget</a></span> <span class="operator">*</span>parent)
      : <span class="type"><a href="qwidget.html">QWidget</a></span>(parent)
  {
      <span class="type"><a href="../qtcore/qfile.html">QFile</a></span> dictionaryFile(<span class="type"><a href="../qtcore/qstring.html#QStringLiteral">QStringLiteral</a></span>(<span class="string">&quot;:/dictionary/words.txt&quot;</span>));
      dictionaryFile<span class="operator">.</span>open(<span class="type"><a href="../qtcore/qfile.html">QFile</a></span><span class="operator">::</span>ReadOnly);
      <span class="type"><a href="../qtcore/qtextstream.html">QTextStream</a></span> inputStream(<span class="operator">&amp;</span>dictionaryFile);

</pre>
<p><a href="../qtcore/qfile.html">QFile</a> 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 <a href="../qtcore/qtextstream.html">QTextStream</a> or <a href="../qtcore/qdatastream.html">QDataStream</a>. We have chosen to read the contents of the file using the <a href="../qtcore/qtextstream.html">QTextStream</a> class that provides a convenient interface for reading and writing text.</p>
<p>We then create the fridge magnets. As long as there is data (the <a href="../qtcore/qtextstream.html#atEnd">QTextStream::atEnd</a>() method returns true if there is no more data to be read from the stream), we read one line at a time using <a href="../qtcore/qtextstream.html">QTextStream</a>'s <a href="../qtcore/qtextstream.html#readLine">readLine()</a> method.</p>
<pre class="cpp">

      <span class="type">int</span> x <span class="operator">=</span> <span class="number">5</span>;
      <span class="type">int</span> y <span class="operator">=</span> <span class="number">5</span>;

      <span class="keyword">while</span> (<span class="operator">!</span>inputStream<span class="operator">.</span>atEnd()) {
          <span class="type"><a href="../qtcore/qstring.html">QString</a></span> word;
          inputStream <span class="operator">&gt;</span><span class="operator">&gt;</span> word;
          <span class="keyword">if</span> (<span class="operator">!</span>word<span class="operator">.</span>isEmpty()) {
              DragLabel <span class="operator">*</span>wordLabel <span class="operator">=</span> <span class="keyword">new</span> DragLabel(word<span class="operator">,</span> <span class="keyword">this</span>);
              wordLabel<span class="operator">-</span><span class="operator">&gt;</span>move(x<span class="operator">,</span> y);
              wordLabel<span class="operator">-</span><span class="operator">&gt;</span>show();
              wordLabel<span class="operator">-</span><span class="operator">&gt;</span>setAttribute(<span class="type"><a href="../qtcore/qt.html">Qt</a></span><span class="operator">::</span>WA_DeleteOnClose);
              x <span class="operator">+</span><span class="operator">=</span> wordLabel<span class="operator">-</span><span class="operator">&gt;</span>width() <span class="operator">+</span> <span class="number">2</span>;
              <span class="keyword">if</span> (x <span class="operator">&gt;</span><span class="operator">=</span> <span class="number">245</span>) {
                  x <span class="operator">=</span> <span class="number">5</span>;
                  y <span class="operator">+</span><span class="operator">=</span> wordLabel<span class="operator">-</span><span class="operator">&gt;</span>height() <span class="operator">+</span> <span class="number">2</span>;
              }
          }
      }

</pre>
<p>For each line, we create a <code>DragLabel</code> object using the read line as text, we calculate its position and ensure that it is visible by calling the <a href="qwidget.html#show">QWidget::show</a>() method. We set the <a href="../qtcore/qt.html#WidgetAttribute-enum">Qt::WA_DeleteOnClose</a> attribute on each label to ensure that any unused labels will be deleted; we will need to create new labels and delete old ones when they are dragged around, and this ensures that the example does not leak memory.</p>
<p>We also set the <code>FridgeMagnets</code> widget's palette, minimum size and window title.</p>
<pre class="cpp">

      <span class="type"><a href="../qtgui/qpalette.html">QPalette</a></span> newPalette <span class="operator">=</span> palette();
      newPalette<span class="operator">.</span>setColor(<span class="type"><a href="../qtgui/qpalette.html">QPalette</a></span><span class="operator">::</span>Window<span class="operator">,</span> <span class="type"><a href="../qtcore/qt.html">Qt</a></span><span class="operator">::</span>white);
      setPalette(newPalette);

      setMinimumSize(<span class="number">400</span><span class="operator">,</span> <a href="../qtcore/qtglobal.html#qMax">qMax</a>(<span class="number">200</span><span class="operator">,</span> y));
      setWindowTitle(tr(<span class="string">&quot;Fridge Magnets&quot;</span>));

</pre>
<p>Finally, to enable our user to move the fridge magnets around, we must also set the <code>FridgeMagnets</code> widget's <a href="qwidget.html#acceptDrops-prop">acceptDrops</a> property.</p>
<pre class="cpp">

      setAcceptDrops(<span class="keyword">true</span>);
  }

</pre>
<p>Setting this property to true announces to the system that this widget <i>may</i> be able to accept drop events (events that are sent when drag and drop actions are completed). Later, we will implement the functions that ensure that the widget accepts the drop events it is interested in.</p>
<a name="dragging"></a>
<h3 >Dragging</h3>
<p>Let's take a look at the <a href="qwidget.html#mousePressEvent">mousePressEvent()</a> event handler, where drag and drop operations begin:</p>
<pre class="cpp">

  <span class="type">void</span> DragWidget<span class="operator">::</span>mousePressEvent(<span class="type"><a href="../qtgui/qmouseevent.html">QMouseEvent</a></span> <span class="operator">*</span>event)
  {
      DragLabel <span class="operator">*</span>child <span class="operator">=</span> <span class="keyword">static_cast</span><span class="operator">&lt;</span>DragLabel<span class="operator">*</span><span class="operator">&gt;</span>(childAt(event<span class="operator">-</span><span class="operator">&gt;</span>pos()));
      <span class="keyword">if</span> (<span class="operator">!</span>child)
          <span class="keyword">return</span>;

      <span class="type"><a href="../qtcore/qpoint.html">QPoint</a></span> hotSpot <span class="operator">=</span> event<span class="operator">-</span><span class="operator">&gt;</span>pos() <span class="operator">-</span> child<span class="operator">-</span><span class="operator">&gt;</span>pos();

      <span class="type"><a href="../qtcore/qbytearray.html">QByteArray</a></span> itemData;
      <span class="type"><a href="../qtcore/qdatastream.html">QDataStream</a></span> dataStream(<span class="operator">&amp;</span>itemData<span class="operator">,</span> <span class="type"><a href="../qtcore/qiodevice.html">QIODevice</a></span><span class="operator">::</span>WriteOnly);
      dataStream <span class="operator">&lt;</span><span class="operator">&lt;</span> child<span class="operator">-</span><span class="operator">&gt;</span>labelText() <span class="operator">&lt;</span><span class="operator">&lt;</span> <span class="type"><a href="../qtcore/qpoint.html">QPoint</a></span>(hotSpot);

</pre>
<p>Mouse events occur when a mouse button is pressed or released inside a widget, or when the mouse cursor is moved. By reimplementing the <a href="qwidget.html#mousePressEvent">mousePressEvent()</a> method we ensure that we will receive mouse press events for the widget containing the fridge magnets.</p>
<p>Whenever we receive such an event, we first check to see if the position of the click coincides with one of the labels. If not, we simply return.</p>
<p>If the user clicked a label, we determine the position of the <i>hot spot</i> (the position of the click relative to the top-left corner of the label). We create a byte array to store the label's text and the hot spot, and we use a <a href="../qtcore/qdatastream.html">QDataStream</a> object to stream the data into the byte array.</p>
<p>With all the information in place, we create a new <a href="../qtcore/qmimedata.html">QMimeData</a> object. As mentioned above, <a href="../qtcore/qmimedata.html">QMimeData</a> objects associate the data that they hold with the corresponding MIME types to ensure that information can be safely transferred between applications. The <a href="../qtcore/qmimedata.html#setData">setData()</a> method sets the data associated with a given MIME type. In our case, we associate our item data with the custom <code>application/x-fridgemagnet</code> type.</p>
<pre class="cpp">

      <span class="type"><a href="../qtcore/qmimedata.html">QMimeData</a></span> <span class="operator">*</span>mimeData <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="../qtcore/qmimedata.html">QMimeData</a></span>;
      mimeData<span class="operator">-</span><span class="operator">&gt;</span>setData(fridgetMagnetsMimeType()<span class="operator">,</span> itemData);
      mimeData<span class="operator">-</span><span class="operator">&gt;</span>setText(child<span class="operator">-</span><span class="operator">&gt;</span>labelText());

</pre>
<p>Note that we also associate the magnet's text with the <code>text/plain</code> MIME type using <a href="../qtcore/qmimedata.html">QMimeData</a>'s <a href="../qtcore/qmimedata.html#setText">setText()</a> method. Below, we will see how our widget detects both these MIME types with its event handlers.</p>
<p>Finally, we create a <a href="../qtgui/qdrag.html">QDrag</a> object. It is the <a href="../qtgui/qdrag.html">QDrag</a> 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 <a href="../qtcore/qmimedata.html">QMimeData</a> object. When we call <a href="../qtgui/qdrag.html">QDrag</a>'s <a href="../qtgui/qdrag.html#setMimeData">setMimeData()</a> method the ownership of our item data is transferred to the <a href="../qtgui/qdrag.html">QDrag</a> object.</p>
<p>We call the <a href="../qtgui/qdrag.html#setPixmap">setPixmap()</a> function 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 simply use the pixmap used by the label itself to make it look like the fridge magnet itself is being moved.</p>
<pre class="cpp">

      <span class="type"><a href="../qtgui/qdrag.html">QDrag</a></span> <span class="operator">*</span>drag <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="../qtgui/qdrag.html">QDrag</a></span>(<span class="keyword">this</span>);
      drag<span class="operator">-</span><span class="operator">&gt;</span>setMimeData(mimeData);
      drag<span class="operator">-</span><span class="operator">&gt;</span>setPixmap(<span class="operator">*</span>child<span class="operator">-</span><span class="operator">&gt;</span>pixmap());
      drag<span class="operator">-</span><span class="operator">&gt;</span>setHotSpot(hotSpot);

      child<span class="operator">-</span><span class="operator">&gt;</span>hide();

</pre>
<p>We also specify the cursor's hot spot, its position relative to the top-level corner of the drag pixmap, to be the point we calculated above. This makes the process of dragging the label feel more natural because the cursor always points to the same place on the label during the drag operation.</p>
<p>We start the drag operation using <a href="../qtgui/qdrag.html">QDrag</a>'s <a href="../qtgui/qdrag.html#exec">exec()</a> function, requesting that the magnet is copied when the drag is completed.</p>
<pre class="cpp">

      <span class="keyword">if</span> (drag<span class="operator">-</span><span class="operator">&gt;</span>exec(<span class="type"><a href="../qtcore/qt.html">Qt</a></span><span class="operator">::</span>MoveAction <span class="operator">|</span> <span class="type"><a href="../qtcore/qt.html">Qt</a></span><span class="operator">::</span>CopyAction<span class="operator">,</span> <span class="type"><a href="../qtcore/qt.html">Qt</a></span><span class="operator">::</span>CopyAction) <span class="operator">=</span><span class="operator">=</span> <span class="type"><a href="../qtcore/qt.html">Qt</a></span><span class="operator">::</span>MoveAction)
          child<span class="operator">-</span><span class="operator">&gt;</span>close();
      <span class="keyword">else</span>
          child<span class="operator">-</span><span class="operator">&gt;</span>show();
  }

</pre>
<p>The function returns the drop action actually performed by the user (this can be either a copy or a move action in this case); if this action is equal to <a href="../qtcore/qt.html#DropAction-enum">Qt::MoveAction</a> we will close the activated fridge magnet widget because we will create a new one to replace it (see the <a href="qtwidgets-draganddrop-fridgemagnets-example.html#drop">dropEvent()</a> implementation). Otherwise, if the drop is outside our main widget, we simply show the widget in its original position.</p>
<a name="dropping"></a>
<h3 >Dropping</h3>
<p>When a a drag and drop action enters our widget, we will receive a drag enter <i>event</i>. <a href="../qtgui/qdragenterevent.html">QDragEnterEvent</a> inherits most of its functionality from <a href="../qtgui/qdragmoveevent.html">QDragMoveEvent</a>, which in turn inherits most of its functionality from <a href="../qtgui/qdropevent.html">QDropEvent</a>. 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.</p>
<p>In our <code>dragEnterEvent()</code> implementation, we first determine whether we support the event's MIME type or not:</p>
<pre class="cpp">

  <span class="type">void</span> DragWidget<span class="operator">::</span>dragEnterEvent(<span class="type"><a href="../qtgui/qdragenterevent.html">QDragEnterEvent</a></span> <span class="operator">*</span>event)
  {
      <span class="keyword">if</span> (event<span class="operator">-</span><span class="operator">&gt;</span>mimeData()<span class="operator">-</span><span class="operator">&gt;</span>hasFormat(fridgetMagnetsMimeType())) {
          <span class="keyword">if</span> (children()<span class="operator">.</span>contains(event<span class="operator">-</span><span class="operator">&gt;</span>source())) {
              event<span class="operator">-</span><span class="operator">&gt;</span>setDropAction(<span class="type"><a href="../qtcore/qt.html">Qt</a></span><span class="operator">::</span>MoveAction);
              event<span class="operator">-</span><span class="operator">&gt;</span>accept();
          } <span class="keyword">else</span> {
              event<span class="operator">-</span><span class="operator">&gt;</span>acceptProposedAction();
          }

</pre>
<p>If the type is <code>application/x-fridgemagnet</code> and the event origins from any of this application's fridge magnet widgets, we first set the event's drop action using the <a href="../qtgui/qdropevent.html#setDropAction">QDropEvent::setDropAction</a>() method. An event's drop action is the action to be performed on the data by the target. <a href="../qtcore/qt.html#DropAction-enum">Qt::MoveAction</a> indicates that the data is moved from the source to the target.</p>
<p>Then we call the event's <a href="../qtgui/qdragmoveevent.html#accept-1">accept()</a> 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.</p>
<pre class="cpp">

      } <span class="keyword">else</span> <span class="keyword">if</span> (event<span class="operator">-</span><span class="operator">&gt;</span>mimeData()<span class="operator">-</span><span class="operator">&gt;</span>hasText()) {
          event<span class="operator">-</span><span class="operator">&gt;</span>acceptProposedAction();
      } <span class="keyword">else</span> {
          event<span class="operator">-</span><span class="operator">&gt;</span>ignore();
      }
  }

</pre>
<p>We also accept the proposed action if the event's MIME type is <code>text/plain</code>, i.e&#x2e;, if <a href="../qtcore/qmimedata.html#hasText">QMimeData::hasText</a>() returns true. If the event has any other type, on the other hand, we call the event's <a href="../qtgui/qdragmoveevent.html#ignore-1">ignore()</a> method allowing the event to be propagated further.</p>
<pre class="cpp">

  <span class="type">void</span> DragWidget<span class="operator">::</span>dragMoveEvent(<span class="type"><a href="../qtgui/qdragmoveevent.html">QDragMoveEvent</a></span> <span class="operator">*</span>event)
  {
      <span class="keyword">if</span> (event<span class="operator">-</span><span class="operator">&gt;</span>mimeData()<span class="operator">-</span><span class="operator">&gt;</span>hasFormat(fridgetMagnetsMimeType())) {
          <span class="keyword">if</span> (children()<span class="operator">.</span>contains(event<span class="operator">-</span><span class="operator">&gt;</span>source())) {
              event<span class="operator">-</span><span class="operator">&gt;</span>setDropAction(<span class="type"><a href="../qtcore/qt.html">Qt</a></span><span class="operator">::</span>MoveAction);
              event<span class="operator">-</span><span class="operator">&gt;</span>accept();
          } <span class="keyword">else</span> {
              event<span class="operator">-</span><span class="operator">&gt;</span>acceptProposedAction();
          }
      } <span class="keyword">else</span> <span class="keyword">if</span> (event<span class="operator">-</span><span class="operator">&gt;</span>mimeData()<span class="operator">-</span><span class="operator">&gt;</span>hasText()) {
          event<span class="operator">-</span><span class="operator">&gt;</span>acceptProposedAction();
      } <span class="keyword">else</span> {
          event<span class="operator">-</span><span class="operator">&gt;</span>ignore();
      }
  }

</pre>
<p>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 <a href="qwidget.html#dragMoveEvent">dragMoveEvent()</a> method, and examine the event in the exact same way as we did with drag enter events.</p>
<p>Note that the <a href="qwidget.html#dropEvent">dropEvent()</a> event handler behaves slightly differently: We first get hold of the event's MIME data.</p>
<a name="drop"></a><pre class="cpp">

  <span class="type">void</span> DragWidget<span class="operator">::</span>dropEvent(<span class="type"><a href="../qtgui/qdropevent.html">QDropEvent</a></span> <span class="operator">*</span>event)
  {
      <span class="keyword">if</span> (event<span class="operator">-</span><span class="operator">&gt;</span>mimeData()<span class="operator">-</span><span class="operator">&gt;</span>hasFormat(fridgetMagnetsMimeType())) {
          <span class="keyword">const</span> <span class="type"><a href="../qtcore/qmimedata.html">QMimeData</a></span> <span class="operator">*</span>mime <span class="operator">=</span> event<span class="operator">-</span><span class="operator">&gt;</span>mimeData();

</pre>
<p>The <a href="../qtcore/qmimedata.html">QMimeData</a> class provides a container for data that records information about its MIME type. <a href="../qtcore/qmimedata.html">QMimeData</a> 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.</p>
<p>We retrieve the data associated with the <code>application/x-fridgemagnet</code> MIME type using a data stream in order to create a new <code>DragLabel</code> object.</p>
<pre class="cpp">

          <span class="type"><a href="../qtcore/qbytearray.html">QByteArray</a></span> itemData <span class="operator">=</span> mime<span class="operator">-</span><span class="operator">&gt;</span>data(fridgetMagnetsMimeType());
          <span class="type"><a href="../qtcore/qdatastream.html">QDataStream</a></span> dataStream(<span class="operator">&amp;</span>itemData<span class="operator">,</span> <span class="type"><a href="../qtcore/qiodevice.html">QIODevice</a></span><span class="operator">::</span>ReadOnly);

          <span class="type"><a href="../qtcore/qstring.html">QString</a></span> text;
          <span class="type"><a href="../qtcore/qpoint.html">QPoint</a></span> offset;
          dataStream <span class="operator">&gt;</span><span class="operator">&gt;</span> text <span class="operator">&gt;</span><span class="operator">&gt;</span> offset;

</pre>
<p>The <a href="../qtcore/qdatastream.html">QDataStream</a> class provides serialization of binary data to a <a href="../qtcore/qiodevice.html">QIODevice</a> (a data stream is a binary stream of encoded information which is completely independent of the host computer's operating system, CPU or byte order).</p>
<p>Finally, we create a label and move it to the event's position:</p>
<pre class="cpp">

          DragLabel <span class="operator">*</span>newLabel <span class="operator">=</span> <span class="keyword">new</span> DragLabel(text<span class="operator">,</span> <span class="keyword">this</span>);
          newLabel<span class="operator">-</span><span class="operator">&gt;</span>move(event<span class="operator">-</span><span class="operator">&gt;</span>pos() <span class="operator">-</span> offset);
          newLabel<span class="operator">-</span><span class="operator">&gt;</span>show();
          newLabel<span class="operator">-</span><span class="operator">&gt;</span>setAttribute(<span class="type"><a href="../qtcore/qt.html">Qt</a></span><span class="operator">::</span>WA_DeleteOnClose);

          <span class="keyword">if</span> (event<span class="operator">-</span><span class="operator">&gt;</span>source() <span class="operator">=</span><span class="operator">=</span> <span class="keyword">this</span>) {
              event<span class="operator">-</span><span class="operator">&gt;</span>setDropAction(<span class="type"><a href="../qtcore/qt.html">Qt</a></span><span class="operator">::</span>MoveAction);
              event<span class="operator">-</span><span class="operator">&gt;</span>accept();
          } <span class="keyword">else</span> {
              event<span class="operator">-</span><span class="operator">&gt;</span>acceptProposedAction();
          }

</pre>
<p>If the source of the event is also the widget receiving the drop event, we set the event's drop action to <a href="../qtcore/qt.html#DropAction-enum">Qt::MoveAction</a> and call the event's <a href="../qtgui/qdragmoveevent.html#accept-1">accept()</a> method. Otherwise, we simply accept the proposed action. This means that labels are moved rather than copied in the same window. However, if we drag a label to a second instance of the Fridge Magnets example, the default action is to copy it, leaving the original in the first instance.</p>
<p>If the event's MIME type is <code>text/plain</code> (i.e&#x2e;, if <a href="../qtcore/qmimedata.html#hasText">QMimeData::hasText</a>() returns true) we retrieve its text and split it into words. For each word we create a new <code>DragLabel</code> 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. This lets the user drop selected text from a text editor or Web browser onto the widget to add more fridge magnets.</p>
<pre class="cpp">

      } <span class="keyword">else</span> <span class="keyword">if</span> (event<span class="operator">-</span><span class="operator">&gt;</span>mimeData()<span class="operator">-</span><span class="operator">&gt;</span>hasText()) {
          <span class="type"><a href="../qtcore/qstringlist.html">QStringList</a></span> pieces <span class="operator">=</span> event<span class="operator">-</span><span class="operator">&gt;</span>mimeData()<span class="operator">-</span><span class="operator">&gt;</span>text()<span class="operator">.</span>split(<span class="type"><a href="../qtcore/qregularexpression.html">QRegularExpression</a></span>(<span class="type"><a href="../qtcore/qstring.html#QStringLiteral">QStringLiteral</a></span>(<span class="string">&quot;\\s+&quot;</span>))<span class="operator">,</span>
                               <span class="type"><a href="../qtcore/qstring.html">QString</a></span><span class="operator">::</span>SkipEmptyParts);
          <span class="type"><a href="../qtcore/qpoint.html">QPoint</a></span> position <span class="operator">=</span> event<span class="operator">-</span><span class="operator">&gt;</span>pos();

          foreach (<span class="keyword">const</span> <span class="type"><a href="../qtcore/qstring.html">QString</a></span> <span class="operator">&amp;</span>piece<span class="operator">,</span> pieces) {
              DragLabel <span class="operator">*</span>newLabel <span class="operator">=</span> <span class="keyword">new</span> DragLabel(piece<span class="operator">,</span> <span class="keyword">this</span>);
              newLabel<span class="operator">-</span><span class="operator">&gt;</span>move(position);
              newLabel<span class="operator">-</span><span class="operator">&gt;</span>show();
              newLabel<span class="operator">-</span><span class="operator">&gt;</span>setAttribute(<span class="type"><a href="../qtcore/qt.html">Qt</a></span><span class="operator">::</span>WA_DeleteOnClose);

              position <span class="operator">+</span><span class="operator">=</span> <span class="type"><a href="../qtcore/qpoint.html">QPoint</a></span>(newLabel<span class="operator">-</span><span class="operator">&gt;</span>width()<span class="operator">,</span> <span class="number">0</span>);
          }

          event<span class="operator">-</span><span class="operator">&gt;</span>acceptProposedAction();
      } <span class="keyword">else</span> {
          event<span class="operator">-</span><span class="operator">&gt;</span>ignore();
      }
  }

</pre>
<p>If the event has any other type, we call the event's <a href="../qtgui/qdragmoveevent.html#ignore-1">ignore()</a> method allowing the event to be propagated further.</p>
<a name="summary"></a>
<h2 id="summary">Summary</h2>
<p>We set our main widget's <a href="qwidget.html#acceptDrops-prop">acceptDrops</a> property and reimplemented <a href="qwidget.html">QWidget</a>'s <a href="qwidget.html#dragEnterEvent">dragEnterEvent()</a>, <a href="qwidget.html#dragMoveEvent">dragMoveEvent()</a> and <a href="qwidget.html#dropEvent">dropEvent()</a> event handlers to support content dropped on our widget.</p>
<p>In addition, we reimplemented the <a href="qwidget.html#mousePressEvent">mousePressEvent()</a> function to let the user pick up fridge magnets in the first place.</p>
<p>Because data is communicated using drag and drop operations and encoded using MIME types, you can run more than one instance of this example, and transfer magnets between them.</p>
<p>Files:</p>
<ul>
<li><a href="qtwidgets-draganddrop-fridgemagnets-draglabel-cpp.html">draganddrop/fridgemagnets/draglabel.cpp</a></li>
<li><a href="qtwidgets-draganddrop-fridgemagnets-draglabel-h.html">draganddrop/fridgemagnets/draglabel.h</a></li>
<li><a href="qtwidgets-draganddrop-fridgemagnets-dragwidget-cpp.html">draganddrop/fridgemagnets/dragwidget.cpp</a></li>
<li><a href="qtwidgets-draganddrop-fridgemagnets-dragwidget-h.html">draganddrop/fridgemagnets/dragwidget.h</a></li>
<li><a href="qtwidgets-draganddrop-fridgemagnets-main-cpp.html">draganddrop/fridgemagnets/main.cpp</a></li>
<li><a href="qtwidgets-draganddrop-fridgemagnets-fridgemagnets-pro.html">draganddrop/fridgemagnets/fridgemagnets.pro</a></li>
<li><a href="qtwidgets-draganddrop-fridgemagnets-fridgemagnets-qrc.html">draganddrop/fridgemagnets/fridgemagnets.qrc</a></li>
</ul>
</div>
<!-- @@@draganddrop/fridgemagnets -->
        </div>
       </div>
   </div>
   </div>
</div>
<div class="footer">
   <p>
   <acronym title="Copyright">&copy;</acronym> 2017 The Qt Company Ltd.
   Documentation contributions included herein are the copyrights of
   their respective owners.<br>    The documentation provided herein is licensed under the terms of the    <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation    License version 1.3</a> as published by the Free Software Foundation.<br>    Qt and respective logos are trademarks of The Qt Company Ltd.     in Finland and/or other countries worldwide. All other trademarks are property
   of their respective owners. </p>
</div>
</body>
</html>