Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
finalwidget.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
3
4/*
5finalwidget.cpp
6
7A widget to display an image and a label containing a description.
8*/
9
10#include "finalwidget.h"
11
12#include <QApplication>
13#include <QBuffer>
14#include <QDrag>
15#include <QLabel>
16#include <QMimeData>
17#include <QMouseEvent>
18#include <QVBoxLayout>
19
20FinalWidget::FinalWidget(QWidget *parent, const QString &name,
21 const QSize &labelSize)
22 : QFrame(parent)
23{
24 hasImage = false;
25 imageLabel = new QLabel;
26 imageLabel->setFrameShadow(QFrame::Sunken);
27 imageLabel->setFrameShape(QFrame::StyledPanel);
28 imageLabel->setMinimumSize(labelSize);
29 nameLabel = new QLabel(name);
30
31 QVBoxLayout *layout = new QVBoxLayout(this);
32 layout->addWidget(imageLabel, 1);
33 layout->addWidget(nameLabel, 0);
34}
35
36/*!
37 If the mouse moves far enough when the left mouse button is held down,
38 start a drag and drop operation.
39*/
40
41void FinalWidget::mouseMoveEvent(QMouseEvent *event)
42{
43 if (!(event->buttons() & Qt::LeftButton))
44 return;
45 if ((event->pos() - dragStartPosition).manhattanLength()
46 < QApplication::startDragDistance())
47 return;
48 if (!hasImage)
49 return;
50
51 QDrag *drag = new QDrag(this);
52 QMimeData *mimeData = new QMimeData;
53
54//! [0]
55 QByteArray output;
56 QBuffer outputBuffer(&output);
57 outputBuffer.open(QIODevice::WriteOnly);
58 imageLabel->pixmap().toImage().save(&outputBuffer, "PNG");
59 mimeData->setData("image/png", output);
60//! [0]
61/*
62//! [1]
63 mimeData->setImageData(QVariant(*imageLabel->pixmap()));
64//! [1]
65*/
66 drag->setMimeData(mimeData);
67 drag->setPixmap(imageLabel->pixmap().scaled(64, 64, Qt::KeepAspectRatio));
68//! [2]
69 drag->setHotSpot(QPoint(drag->pixmap().width()/2,
70 drag->pixmap().height()));
71//! [2]
72}
73
74/*!
75 Check for left mouse button presses in order to enable drag and drop.
76*/
77
78void FinalWidget::mousePressEvent(QMouseEvent *event)
79{
80 if (event->button() == Qt::LeftButton)
81 dragStartPosition = event->pos();
82}
83
85{
86 return imageLabel->pixmap();
87}
88
89void FinalWidget::setPixmap(const QPixmap &pixmap)
90{
91 imageLabel->setPixmap(pixmap);
92 hasImage = true;
93}
void mousePressEvent(QMouseEvent *event) override
Check for left mouse button presses in order to enable drag and drop.
void mouseMoveEvent(QMouseEvent *event) override
If the mouse moves far enough when the left mouse button is held down, start a drag and drop operatio...
QPixmap pixmap() const
void setPixmap(const QPixmap &pixmap)