123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- #include "ImageWidget.h"
- #include "ui_ImageWidget.h"
- #include <QPainter>
- 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::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; // 设置正在拖动的标志
- }
- }
- 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; // 重置正在拖动的标志
- }
- }
|