ImageWidget.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include "ImageWidget.h"
  2. #include "ui_ImageWidget.h"
  3. #include <QPainter>
  4. ImageWidget::ImageWidget(QWidget *parent) :
  5. QWidget(parent),
  6. ui(new Ui::ImageWidget),
  7. isDragging(false),
  8. imageOffset(0, 0)
  9. {
  10. ui->setupUi(this);
  11. }
  12. ImageWidget::~ImageWidget()
  13. {
  14. delete ui;
  15. }
  16. void ImageWidget::setPixmap(const QPixmap& newPixmap) {
  17. this->pixmap = newPixmap;
  18. imageOffset = QPoint(0, 0); // 重置图片偏移量为(0, 0)
  19. update(); // 触发重绘
  20. }
  21. void ImageWidget::paintEvent(QPaintEvent *event) {
  22. QPainter painter(this);
  23. if (!pixmap.isNull()) {
  24. // 计算图片左上角坐标,使得图片中心与控件中心对齐
  25. int centerX = width() / 2;
  26. int centerY = height() / 2;
  27. int pixmapCenterX = pixmap.width() / 2;
  28. int pixmapCenterY = pixmap.height() / 2;
  29. int x = centerX - pixmapCenterX + imageOffset.x();
  30. int y = centerY - pixmapCenterY + imageOffset.y();
  31. painter.drawPixmap(x, y, pixmap);
  32. }
  33. }
  34. void ImageWidget::mousePressEvent(QMouseEvent *event) {
  35. if (event->button() == Qt::LeftButton) {
  36. lastMousePos = event->pos(); // 记录鼠标按下时的位置
  37. isDragging = true; // 设置正在拖动的标志
  38. }
  39. }
  40. void ImageWidget::mouseMoveEvent(QMouseEvent *event) {
  41. if (isDragging && (event->buttons() & Qt::LeftButton)) {
  42. QPoint delta = event->pos() - lastMousePos; // 计算鼠标移动的偏移量
  43. imageOffset += delta; // 更新图片的偏移量
  44. lastMousePos = event->pos(); // 更新鼠标位置
  45. update();
  46. }
  47. }
  48. void ImageWidget::mouseReleaseEvent(QMouseEvent *event) {
  49. if (event->button() == Qt::LeftButton) {
  50. isDragging = false; // 重置正在拖动的标志
  51. }
  52. }