Qt 之Alt+滚轮缩放无响应

        在日常开发中,特别是在一些对图形进行缩放等鼠标操作时,难免会用到组合键+鼠标来实现一些特殊功能,例如需要用到shift+鼠标、ctrl+鼠标、alt+鼠标……来完成如多选、缩放等操作。

        而最近针对用QCustomPlot来Atl+滚轮来做定制化图形缩放功能时,发现按下Alt按键后,无法进行滚轮缩放了,好奇心驱使下去翻看源码,发现并不是无响应,而是问题出现在这里了

发现当按下Alt按键时,Qt获取到的滚轮坐标的y值都是0,导致后面计算得到factor都是1,因此缩放不起作用。

然后进一步测试测试,发现当按下Alt时Qt获取到的滚轮坐标的x、y值是倒置的(使用的Qt版本是5.15.2)

        在新的版本中获取鼠标滚轮坐标的方式变了,旧的接口已经被丢弃了,而新版的Qt中,当Atl按键被按下时,获取到的滚轮坐标的X值和Y值发生了导致,因此在按常规的方法进行处理时,会出现滚动滚轮无响应的现象。

        因此在实际的应用中,当我们需要使用Alt+鼠标滚轮来实现某些定制化功能时,在进行计算时需要把获取到的鼠标滚轮的X和Y值进行互换,即

// 当Alt按下时
double delta_x = event->angleDelta().y();
double delta_y = event->angleDelta().x();

        如此便可获取想要的值来实现想要的功能了。

        若本文对您有帮助请点个赞,若有写的不对的地方麻烦指出,海涵海涵!^-^

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
import QtQuick 2.4 import QtQuick.Controls 2.5 import QtQuick.Window 2.3 ApplicationWindow { visible: true width: 800 height: 600 title: "Drawing Board Example" Rectangle { width: 600 height: 400 Canvas { id: canvas anchors.fill: parent onPaint: { // 设置画布初始位置和网格线样式 ctx.translate(width / 2, height / 2); ctx.lineWidth = 0.5; ctx.strokeStyle = '#ddd'; // 绘制网格线 for (let i = -width / 2; i <= width / 2; i += 10) { ctx.beginPath(); ctx.moveTo(i, -height / 2); ctx.lineTo(i, height / 2); ctx.stroke(); } for (let i = -height / 2; i <= height / 2; i += 10) { ctx.beginPath(); ctx.moveTo(-width / 2, i); ctx.lineTo(width / 2, i); ctx.stroke(); } let isDragging = false; let rect = { x: 0, y: 0, width: 100, height: 100, angle: 0 }; // 绘制矩形 function drawRect() { ctx.clearRect(-width / 2, -height / 2, width, height); ctx.save(); ctx.translate(rect.x, rect.y); ctx.rotate(rect.angle); ctx.fillRect(-rect.width / 2, -rect.height / 2, rect.width, rect.height); ctx.restore(); } // 鼠标事件处理 canvas.mousePressEvent.connect(function (e) { const x = e.x - width / 2; const y = e.y - height / 2; if (x > rect.x - rect.width / 2 && x < rect.x + rect.width / 2 && y > rect.y - rect.height / 2 && y < rect.y + rect.height / 2) { isDragging = true; } }); canvas.mouseMoveEvent.connect(function (e) { if (isDragging) { const x = e.x - width / 2; const y = e.y - height / 2; rect.x = x; rect.y = y; drawRect(); } }); canvas.mouseReleaseEvent.connect(function () { isDragging = false; }); canvas.wheelEvent.connect(function (e) { const zoom = e.angleDelta.y() > 0 ? 0.9 : 1.1; rect.width *= zoom; rect.height *= zoom; drawRect(); }); canvas.contextMenuEvent.connect(function (e) { e.accepted = true; rect.angle += Math.PI / 4; drawRect(); }); drawRect(); } } } }在这段代码中采用了上述的需求实现方法,但是在运行时,所有的需求都没能够完成,其中警告信息为var "i"used before its declaration. "i" is declarad more than once.报错信息为ReferenceError: ctx is not defined。应该如何修改这段代码使其能够正常完成需求
06-09
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值