#ifndef IMAGEWIDGET_H #define IMAGEWIDGET_H #include #include #include namespace Ui { class ImageWidget; } class ImageWidget : public QWidget { Q_OBJECT public: explicit ImageWidget(QWidget *parent = nullptr); ~ImageWidget(); void setPixmap(const QPixmap& pixmap) { this->pixmap = pixmap; update(); // 触发重绘 } protected: void paintEvent(QPaintEvent* event) override { QPainter painter(this); if (!pixmap.isNull()) { // 获取窗口的中心点坐标 int centerX = width() / 2; int centerY = height() / 2; // 计算pixmap的中心点坐标 int pixmapCenterX = pixmap.width() / 2; int pixmapCenterY = pixmap.height() / 2; // 计算pixmap左上角的坐标,使其中心与窗口中心对齐 int x = centerX - pixmapCenterX; int y = centerY - pixmapCenterY; // 在计算出的位置绘制 pixmap painter.drawPixmap(x, y, pixmap); } } private: Ui::ImageWidget *ui; QPixmap pixmap; }; #endif // IMAGEWIDGET_H