1
0

DnD to load image file

This commit is contained in:
Gary Wang
2019-09-29 15:52:35 +08:00
parent a86efaaeb3
commit 771ec335fe
6 changed files with 197 additions and 46 deletions

View File

@@ -1,8 +1,12 @@
#include "graphicsview.h"
#include "graphicsscene.h"
#include <QDebug>
#include <QMouseEvent>
#include <QScrollBar>
#include <QMimeData>
#include <QImageReader>
GraphicsView::GraphicsView(QWidget *parent)
: QGraphicsView (parent)
@@ -12,6 +16,27 @@ GraphicsView::GraphicsView(QWidget *parent)
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setStyleSheet("background-color: rgba(0, 0, 0, 180);"
"border-radius: 3px;");
setAcceptDrops(true);
}
void GraphicsView::showImage(const QPixmap &pixmap)
{
scene()->showImage(pixmap);
}
void GraphicsView::showText(const QString &text)
{
scene()->showText(text);
}
GraphicsScene *GraphicsView::scene() const
{
return qobject_cast<GraphicsScene*>(QGraphicsView::scene());
}
void GraphicsView::setScene(GraphicsScene *scene)
{
return QGraphicsView::setScene(scene);
}
void GraphicsView::mousePressEvent(QMouseEvent *event)
@@ -57,3 +82,52 @@ void GraphicsView::wheelEvent(QWheelEvent *event)
scale(0.8, 0.8);
}
}
void GraphicsView::dragEnterEvent(QDragEnterEvent *event)
{
if (event->mimeData()->hasUrls() || event->mimeData()->hasImage() || event->mimeData()->hasText()) {
event->acceptProposedAction();
} else {
event->ignore();
}
qDebug() << event->mimeData() << "Drag Enter Event"
<< event->mimeData()->hasUrls() << event->mimeData()->hasImage()
<< event->mimeData()->formats() << event->mimeData()->hasFormat("text/uri-list");
return QGraphicsView::dragEnterEvent(event);
}
void GraphicsView::dragMoveEvent(QDragMoveEvent *event)
{
Q_UNUSED(event);
// by default, QGraphicsView/Scene will ignore the action if there are no QGraphicsItem under cursor.
// We actually doesn't care and would like to keep the drag event as-is, so just do nothing here.
}
void GraphicsView::dropEvent(QDropEvent *event)
{
event->acceptProposedAction();
const QMimeData * mimeData = event->mimeData();
if (mimeData->hasUrls()) {
QUrl url(mimeData->urls().first());
QImageReader imageReader(url.toLocalFile());
QImage::Format imageFormat = imageReader.imageFormat();
if (imageFormat == QImage::Format_Invalid) {
showText("File is not a valid image");
} else {
showImage(QPixmap::fromImageReader(&imageReader));
}
} else if (mimeData->hasImage()) {
QImage img = qvariant_cast<QImage>(mimeData->imageData());
QPixmap pixmap = QPixmap::fromImage(img);
if (pixmap.isNull()) {
showText("Image data is invalid");
} else {
showImage(pixmap);
}
} else if (mimeData->hasText()) {
showText(mimeData->text());
}
}