ImageWidget.h 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #ifndef IMAGEWIDGET_H
  2. #define IMAGEWIDGET_H
  3. #include <QWidget>
  4. #include <QStyleOption>
  5. #include <QPainter>
  6. namespace Ui {
  7. class ImageWidget;
  8. }
  9. class ImageWidget : public QWidget
  10. {
  11. Q_OBJECT
  12. public:
  13. explicit ImageWidget(QWidget *parent = nullptr);
  14. ~ImageWidget();
  15. void setPixmap(const QPixmap& pixmap) {
  16. this->pixmap = pixmap;
  17. update(); // 触发重绘
  18. }
  19. protected:
  20. void paintEvent(QPaintEvent* event) override {
  21. QPainter painter(this);
  22. if (!pixmap.isNull()) {
  23. // 获取窗口的中心点坐标
  24. int centerX = width() / 2;
  25. int centerY = height() / 2;
  26. // 计算pixmap的中心点坐标
  27. int pixmapCenterX = pixmap.width() / 2;
  28. int pixmapCenterY = pixmap.height() / 2;
  29. // 计算pixmap左上角的坐标,使其中心与窗口中心对齐
  30. int x = centerX - pixmapCenterX;
  31. int y = centerY - pixmapCenterY;
  32. // 在计算出的位置绘制 pixmap
  33. painter.drawPixmap(x, y, pixmap);
  34. }
  35. }
  36. private:
  37. Ui::ImageWidget *ui;
  38. QPixmap pixmap;
  39. };
  40. #endif // IMAGEWIDGET_H