Qt 5.10 Book Examples
Drag.h
Go to the documentation of this file.
1 // ======================================================================
2 // Drag.h
3 // ======================================================================
4 // This file is a part of the book
5 // "Qt 5.10 Professional programming with C++"
6 // http://qt-book.com
7 // ======================================================================
8 // Copyright (c) 2017 by Max Schlee
9 // ======================================================================
10 
11 #pragma once
12 
13 #include <QtWidgets>
14 
15 // ======================================================================
16 class Drag : public QLabel {
17 Q_OBJECT
18 private:
19  QPoint m_ptDragPos;
20 
21  void startDrag()
22  {
23  QMimeData* pMimeData = new QMimeData;
24  pMimeData->setText(text());
25 
26  QDrag* pDrag = new QDrag(this);
27  pDrag->setMimeData(pMimeData);
28  pDrag->setPixmap(QPixmap(":/img1.png"));
29  pDrag->exec(Qt::MoveAction);
30  }
31 
32 protected:
33  virtual void mousePressEvent(QMouseEvent* pe)
34  {
35  if (pe->button() == Qt::LeftButton) {
36  m_ptDragPos = pe->pos();
37  }
38  QWidget::mousePressEvent(pe);
39  }
40 
41  virtual void mouseMoveEvent (QMouseEvent* pe)
42  {
43  if (pe->buttons() & Qt::LeftButton) {
44  int distance = (pe->pos() - m_ptDragPos).manhattanLength();
45  if (distance > QApplication::startDragDistance()) {
46  startDrag();
47  }
48  }
49  QWidget::mouseMoveEvent(pe);
50  }
51 
52 public:
53  Drag(QWidget* pwgt = 0) : QLabel("This is a draggable text", pwgt)
54  {
55  }
56 };
virtual void mouseMoveEvent(QMouseEvent *pe)
Definition: Drag.h:41
virtual void mousePressEvent(QMouseEvent *pe)
Definition: Drag.h:33
Definition: Drag.h:16
Drag(QWidget *pwgt=0)
Definition: Drag.h:53