Qt 5.10 Book Examples
Widget.cpp
Go to the documentation of this file.
1 // ======================================================================
2 // Widget.cpp
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 #include <QtWidgets>
12 #include "Widget.h"
13 #include "WidgetDrag.h"
14 
15 // ----------------------------------------------------------------------
16 Widget::Widget(QWidget* pwgt/*=0*/) : QLabel(pwgt)
17 {
18  setAcceptDrops(true);
19 }
20 
21 // ----------------------------------------------------------------------
22 void Widget::startDrag()
23 {
24  WidgetDrag* pDrag = new WidgetDrag(this);
25  pDrag->setWidget(this);
26  pDrag->exec(Qt::CopyAction);
27 }
28 
29 // ----------------------------------------------------------------------
30 /*virtual*/ void Widget::mousePressEvent(QMouseEvent* pe)
31 {
32  if (pe->button() == Qt::LeftButton) {
33  m_ptDragPos = pe->pos();
34  }
35  QWidget::mousePressEvent(pe);
36 }
37 
38 // ----------------------------------------------------------------------
39 /*virtual*/ void Widget::mouseMoveEvent(QMouseEvent* pe)
40 {
41  if (pe->buttons() & Qt::LeftButton) {
42  int distance = (pe->pos() - m_ptDragPos).manhattanLength();
43  if (distance > QApplication::startDragDistance()) {
44  startDrag();
45  }
46  }
47  QWidget::mouseMoveEvent(pe);
48 }
49 
50 // ----------------------------------------------------------------------
51 /*virtual*/ void Widget::dragEnterEvent(QDragEnterEvent* pe)
52 {
53  if (pe->mimeData()->hasFormat(WidgetMimeData::mimeType())) {
54  pe->acceptProposedAction();
55  }
56 }
57 
58 // ----------------------------------------------------------------------
59 /*virtual*/ void Widget::dropEvent(QDropEvent* pe)
60 {
61  const WidgetMimeData* pmmd =
62  dynamic_cast<const WidgetMimeData*>(pe->mimeData());
63  if (pmmd) {
64  QWidget* pwgt = pmmd->widget();
65  QString str("Widget is dropped\n ObjectName:%1");
66  setText(str.arg(pwgt->objectName()));
67  }
68 }
69 
virtual void dropEvent(QDropEvent *)
Definition: Widget.cpp:59
virtual void mouseMoveEvent(QMouseEvent *)
Definition: Widget.cpp:39
virtual void dragEnterEvent(QDragEnterEvent *)
Definition: Widget.cpp:51
virtual void mousePressEvent(QMouseEvent *)
Definition: Widget.cpp:30
QWidget * widget() const
Definition: WidgetDrag.h:40
Widget(QWidget *pwgt=0)
Definition: Widget.cpp:16
void setWidget(QWidget *pwgt)
Definition: WidgetDrag.h:53
static QString mimeType()
Definition: WidgetDrag.h:29