1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- #include "ImageWidget.h"
- #include "ui_ImageWidget.h"
- #include <QPainter>
- #include <QDebug>
- ImageWidget::ImageWidget(QWidget *parent) :
- QWidget(parent),
- ui(new Ui::ImageWidget),
- isDragging(false),
- imageOffset(0, 0)
- {
- ui->setupUi(this);
- }
- ImageWidget::~ImageWidget()
- {
- delete ui;
- }
- void ImageWidget::setPixmap(const QPixmap& newPixmap) {
- this->pixmap = newPixmap;
- imageOffset = QPoint(0, 0);
- setCursor(Qt::ArrowCursor);
- update();
- }
- void ImageWidget::setPixmapAndPoint(const QPixmap& pixmap, double previousScaleFactor, qreal scaleFactor, QPoint mousePos) {
- this->pixmap = pixmap;
- QPointF imagePos = (mousePos - imageOffset) / previousScaleFactor;
- imageOffset = mousePos - imagePos * scaleFactor;
- update();
- }
- void ImageWidget::clearPixmap() {
- this->pixmap = QPixmap();
- update();
- }
- void ImageWidget::paintEvent(QPaintEvent *event) {
- QPainter painter(this);
- if (!pixmap.isNull()) {
-
- int pixmapWidth = pixmap.width();
- int pixmapHeight = pixmap.height();
- int widgetWidth = width();
- int widgetHeight = height();
-
- if (pixmapWidth < widgetWidth) {
- imageOffset.setX(0);
- } else {
-
- imageOffset.setX(qMin(0.0, qMax(static_cast<qreal>(widgetWidth - pixmapWidth), imageOffset.x())));
- }
-
- if (pixmapHeight < widgetHeight) {
- imageOffset.setY(0);
- } else {
-
- imageOffset.setY(qMin(0.0, qMax(static_cast<qreal>(widgetHeight - pixmapHeight), imageOffset.y())));
- }
- painter.drawPixmap(imageOffset.x(), imageOffset.y(), pixmap);
- }
- }
- void ImageWidget::mousePressEvent(QMouseEvent *event) {
- if (event->button() == Qt::LeftButton) {
- lastMousePos = event->pos();
- isDragging = true;
- setCursor(Qt::OpenHandCursor);
- }
- }
- void ImageWidget::mouseMoveEvent(QMouseEvent *event) {
- if (isDragging && (event->buttons() & Qt::LeftButton)) {
- QPoint delta = event->pos() - lastMousePos;
- imageOffset += delta;
- lastMousePos = event->pos();
- update();
- }
- }
- void ImageWidget::mouseReleaseEvent(QMouseEvent *event) {
- if (event->button() == Qt::LeftButton) {
- isDragging = false;
- setCursor(Qt::ArrowCursor);
- }
- }
- void ImageWidget::mouseDoubleClickEvent(QMouseEvent *event){
- if (event->type() == QEvent::MouseButtonDblClick) {
-
- sendDoubleClicksignal();
- }
- QWidget::mouseDoubleClickEvent(event);
- }
|