1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- #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); // 重置图片偏移量为(0, 0)
- update(); // 触发重绘
- }
- void ImageWidget::setPixmapAndPoint(const QPixmap& pixmap){
- this->pixmap = pixmap;
- update();
- }
- void ImageWidget::paintEvent(QPaintEvent *event) {
- QPainter painter(this);
- if (!pixmap.isNull()) {
- // 计算图片左上角坐标,使得图片中心与控件中心对齐
- int centerX = width() / 2;
- int centerY = height() / 2;
- int pixmapCenterX = pixmap.width() / 2;
- int pixmapCenterY = pixmap.height() / 2;
- int x = centerX - pixmapCenterX + imageOffset.x();
- int y = centerY - pixmapCenterY + imageOffset.y();
- painter.drawPixmap(x, 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);
- }
|