qt 重写继承QGraphicsView,打开图像显示时自适应,以原始的图像大小显示鼠标移动的坐标,CTRL和鼠标左键按下可移动图像,鼠标右键出现菜单栏,鼠标滚轮可放大缩小
时间: 2023-05-17 14:02:33 浏览: 139
您可以使用以下代码实现:
```
class CustomGraphicsView : public QGraphicsView
{
public:
CustomGraphicsView(QWidget *parent = nullptr) : QGraphicsView(parent)
{
setDragMode(QGraphicsView::ScrollHandDrag);
setRenderHint(QPainter::Antialiasing);
setRenderHint(QPainter::SmoothPixmapTransform);
setOptimizationFlag(QGraphicsView::DontAdjustForAntialiasing, true);
setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
setResizeAnchor(QGraphicsView::AnchorUnderMouse);
setInteractive(true);
}
protected:
void resizeEvent(QResizeEvent *event) override
{
QGraphicsView::resizeEvent(event);
fitInView(sceneRect(), Qt::KeepAspectRatio);
}
void wheelEvent(QWheelEvent *event) override
{
if (event->modifiers() & Qt::ControlModifier) {
if (event->delta() > 0) {
scale(1.1, 1.1);
} else {
scale(0.9, 0.9);
}
} else {
QGraphicsView::wheelEvent(event);
}
}
void mousePressEvent(QMouseEvent *event) override
{
if (event->button() == Qt::RightButton) {
// show menu
} else {
QGraphicsView::mousePressEvent(event);
}
}
void mouseMoveEvent(QMouseEvent *event) override
{
QPointF scenePos = mapToScene(event->pos());
// display scenePos
QGraphicsView::mouseMoveEvent(event);
}
};
```
这个类继承自 QGraphicsView,实现了自适应、缩放、拖拽、鼠标移动等功能。您可以在您的程序中使用这个类来显示图像。
阅读全文