summaryrefslogtreecommitdiff
path: root/examples/svg/draganddrop/delayedencoding/sourcewidget.cpp
blob: a782e1bb8dd10e239b3e6395229b20c798386772 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Copyright (C) 2017 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause

#include <QtWidgets>
#include <QtSvg>
#include <QtSvgWidgets>
#include "mimedata.h"
#include "sourcewidget.h"

SourceWidget::SourceWidget(QWidget *parent)
    : QWidget(parent)
{
    QFile imageFile(":/images/example.svg");
    imageFile.open(QIODevice::ReadOnly);
    imageData = imageFile.readAll();
    imageFile.close();

    QScrollArea *imageArea = new QScrollArea;
    imageLabel = new QSvgWidget;
    imageLabel->renderer()->load(imageData);
    imageArea->setWidget(imageLabel);
    //imageLabel->setMinimumSize(imageLabel->renderer()->viewBox().size());

    QLabel *instructTopLabel = new QLabel(tr("This is an SVG drawing:"));
    QLabel *instructBottomLabel = new QLabel(
        tr("Drag the icon to copy the drawing as a PNG file:"));
    instructBottomLabel->setWordWrap(true);
    QPushButton *dragIcon = new QPushButton(tr("Export"));
    dragIcon->setIcon(QIcon(":/images/drag.png"));

    connect(dragIcon, &QPushButton::pressed, this, &SourceWidget::startDrag);

    QGridLayout *layout = new QGridLayout;
    layout->addWidget(instructTopLabel, 0, 0, 1, 2);
    layout->addWidget(imageArea, 1, 0, 2, 2);
    layout->addWidget(instructBottomLabel, 3, 0);
    layout->addWidget(dragIcon, 3, 1);
    setLayout(layout);
    setWindowTitle(tr("Delayed Encoding"));
}

//![1]
void SourceWidget::createData(const QString &mimeType)
{
    if (mimeType != "image/png")
        return;

    QImage image(imageLabel->size(), QImage::Format_RGB32);
    QPainter painter;
    painter.begin(&image);
    imageLabel->renderer()->render(&painter);
    painter.end();

    QByteArray data;
    QBuffer buffer(&data);
    buffer.open(QIODevice::WriteOnly);
    image.save(&buffer, "PNG");
    buffer.close();

    mimeData->setData("image/png", data);
}
//![1]

//![0]
void SourceWidget::startDrag()
{
    mimeData = new MimeData;

    connect(mimeData, &MimeData::dataRequested,
            this, &SourceWidget::createData, Qt::DirectConnection);

    QDrag *drag = new QDrag(this);
    drag->setMimeData(mimeData);
    drag->setPixmap(QPixmap(":/images/drag.png"));

    drag->exec(Qt::CopyAction);
}
//![0]