QScrollArea 以鼠标位置点放大缩小图片,c 实现
时间: 2024-02-18 11:00:23 浏览: 218
您可以使用QScrollBar结合QGraphicsView来实现该功能。以下是一个简单的实现方法:
```c++
#include <QtWidgets>
class ImageViewer : public QGraphicsView {
public:
ImageViewer(QWidget *parent = nullptr) : QGraphicsView(parent) {
scene = new QGraphicsScene(this);
setScene(scene);
setAlignment(Qt::AlignLeft | Qt::AlignTop);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setRenderHint(QPainter::SmoothPixmapTransform);
setDragMode(QGraphicsView::ScrollHandDrag);
}
void setPixmap(const QPixmap &pixmap) {
this->pixmap = pixmap;
scene->clear();
scene->addPixmap(pixmap);
fitInView(scene->sceneRect(), Qt::KeepAspectRatio);
setCursor(Qt::ArrowCursor);
}
protected:
void wheelEvent(QWheelEvent *event) override {
QPoint pos = event->pos();
QPointF scene_pos = mapToScene(pos);
qreal factor = qPow(1.001, event->angleDelta().y());
scale(factor, factor);
QPointF new_scene_pos = mapToScene(pos);
QPointF translate = new_scene_pos - scene_pos;
horizontalScrollBar()->setValue(horizontalScrollBar()->value() + translate.x());
verticalScrollBar()->setValue(verticalScrollBar()->value() + translate.y());
}
void mouseMoveEvent(QMouseEvent *event) override {
QPoint pos = event->pos();
QPointF scene_pos = mapToScene(pos);
if (scene->sceneRect().contains(scene_pos)) {
qreal factor = 1.05;
QPixmap copy = pixmap;
QPainter painter(©);
painter.setRenderHint(QPainter::SmoothPixmapTransform);
painter.translate(pos);
painter.scale(factor, factor);
painter.translate(-pos);
scene->clear();
scene->addPixmap(copy);
setCursor(Qt::OpenHandCursor);
} else {
scene->clear();
scene->addPixmap(pixmap);
setCursor(Qt::ArrowCursor);
}
}
void leaveEvent(QEvent *event) override {
scene->clear();
scene->addPixmap(pixmap);
setCursor(Qt::ArrowCursor);
}
private:
QGraphicsScene *scene;
QPixmap pixmap;
};
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QWidget *widget = new QWidget;
QVBoxLayout *layout = new QVBoxLayout(widget);
ImageViewer *viewer = new ImageViewer(widget);
layout->addWidget(viewer);
QPixmap pixmap(":/image.jpg");
viewer->setPixmap(pixmap);
widget->show();
return app.exec();
}
```
在这个实现中,我们使用QGraphicsView来显示图片,并通过QScrollBar来实现放大和缩小。在鼠标移动事件中,我们将鼠标位置作为放大的中心点,并在场景中绘制一个缩放后的副本。在鼠标离开事件中,我们恢复原始的图片。同时,我们在滚轮事件中实现了按鼠标位置放大和缩小的功能。
阅读全文