QGgraphicsView鼠标缩放

// 20260615 鼠标缩放

void WorkInfoForm::wheelEvent(QWheelEvent* event) {

// 获取当前的鼠标所在的view坐标;

QPointF prev_viewPos = event->position();

// 获取当前鼠标相对于scene的位置;

QPointF prev_scenePos = ui->teach_graphicsView->mapToScene(prev_viewPos.toPoint());

//...计算缩放比例

// 2. 计算缩放因子

double scaleFactor = 1.15;

// 2. 定义最小和最大缩放比例

double currentScale = ui->teach_graphicsView->transform().m11();

复制代码
const double minScale = 1;  // 最小缩小到 10%
const double maxScale = 5.0;  // 最大放大到 500%

//double scaleFactor = 1.15;
bool willZoomIn = (event->angleDelta().y() > 0);

// 3. 计算缩放后的预期比例
double nextScale = willZoomIn ? (currentScale * scaleFactor) : (currentScale / scaleFactor);

// 4. 【关键】如果超出范围,则不执行缩放
if (willZoomIn && nextScale > maxScale) {
    return; // 超过最大限制,忽略本次操作
}
if (!willZoomIn && nextScale < minScale) {
    return; // 低于最小限制,忽略本次操作
}

if (willZoomIn) {
    ui->teach_graphicsView->scale(scaleFactor, scaleFactor);
}
else {
    ui->teach_graphicsView->scale(1 / scaleFactor, 1 / scaleFactor);
}
qDebug() << "缩放比:" << ui->teach_graphicsView->transform().m11();
//ui->teach_graphicsView->scale(scaleTemp, scaleTemp);  //缩放

//20260615 有问题 ui->teach_graphicsView->setSceneRect(ui->teach_graphicsView->mapToScene(this->rect()).boundingRect()); //调整scene,使得scene和view一直,主要是为了排除掉scroll

复制代码
//获取缩放后的scene坐标
QPointF scenePos = ui->teach_graphicsView->mapToScene(prev_viewPos.toPoint());
//获取缩放前后的坐标差值,即为需要进行move的位移
QPointF disPointF = scenePos - prev_scenePos;
//    qDebug()<<prev_scenePos<<" ::: "<<scenePos<<disPointF;
qDebug() << ui->teach_graphicsView->scene()->sceneRect();
//QRectF sceneRect = ui->teach_graphicsView->scene()->sceneRect();
//if (sceneRect.width() > 10000 || sceneRect.height() > 10000) {
//    sceneRect = sceneRect.normalized().adjusted(-5000, -5000, 5000, 5000);
//    ui->teach_graphicsView->scene()->setSceneRect(sceneRect);
//}
//ui->teach_graphicsView->horizontalScrollBar()->setValue(ui->teach_graphicsView->horizontalScrollBar()->value() + disPointF.x());
//ui->teach_graphicsView->verticalScrollBar()->setValue(ui->teach_graphicsView->verticalScrollBar()->value() + disPointF.y());
////调整位置
//ui->teach_graphicsView->scene()->setSceneRect(ui->teach_graphicsView->scene()->sceneRect().x() - disPointF.x(), ui->teach_graphicsView->scene()->sceneRect().y() - disPointF.y(),
// ui->teach_graphicsView->scene()->sceneRect().width(), ui->teach_graphicsView->scene()->sceneRect().height());
//    emit signal_wheel(m_scale);
ui->teach_graphicsView->scene()->update();

}

相关推荐
奇树谦5 小时前
Qt Quick 图片加载与 GPU 纹理机制详解:QImage、QQuickTextureFactory、QSGTexture 与异步加载
开发语言·qt·系统架构
BroNekoX1 天前
我将基于 QtQuick 框架开发的音乐播放器性能做到顶级
qt
小小晓.1 天前
Qt 对话框、QLineEdit 与布局管理实战详解
开发语言·qt
扶尔魔ocy2 天前
【QT入门到晋级】用开源的自定义控件开发
c++·qt·自定义控件
lhbweilai2 天前
QT项目(串口助手)
开发语言·qt
小鱼仙官3 天前
Qt 主界面弹出分界面
开发语言·qt
誰能久伴不乏3 天前
用 UDP 做一条“可靠“的控制通道
c++·qt·网络协议·udp
Bczheng13 天前
VS2022 安装MFC和QT
c++·qt·mfc
会编程的小孩3 天前
8.19号函数
qt
蓝祁子yoky4 天前
Qt学习日记 Day15:网络编程(二)- UDP基础
网络·qt·学习