使用 Qt 的缩放功能
问题描述
当前实现,向视图中心缩放,因此当我们缩放时,左上角的项目或当前鼠标指针不可见.
我想要基于当前鼠标指针的缩放功能,以便当前鼠标指针上的项目向视图中心缩放.
Zoom base on 视区中心代码
缩放总是以鼠标指针为中心 -ndash;鼠标指针的位置只需要成为缩放的原点即可.
听起来很简单,但我在准备演示时有点费劲.(我的线性代数不是很好,抱歉.)不过,我终于让它运行起来了.
我的示例代码testQWidget-Zoom.cc
:
这三行是真正有趣的(在Canvas::wheelEvent()
中):
这是它的样子:
第一张图片是应用程序启动后的快照.
然后我指向红色矩形的中心并轻轻转动轮子.红色矩形按预期围绕鼠标指针增长.
<小时>1st 更新:
而且,这是直接使用屏幕坐标的更新版本(而不是将所有内容都转换为 NDC):
相关的三行变化不大–鼠标坐标直接应用于变换.
顺便说一句.我改变了渲染–它现在可以像我使用的一样缩放线宽
在 Canvas::paintEvent()
中,而不是手动"转换所有点.
我指向蓝色矩形的中心并转动鼠标滚轮后的快照显示:
<小时>2nd 更新:
建议的矩阵操作在
Current implementation, zooms towards the center of View so items present in the top left corner or the current mouse pointer is not visible when we Zoom it.
I want zoom functionality based on the current mouse pointer so items present on the current mouse pointer zoom towards the center of the view.
Code for Zoom base don center of view area
To zoom always centered at mouse pointer – the position of mouse pointer just has to become the origin of scaling.
It sounds that simple but I struggled a bit to prepare a demonstration. (I'm not that good in linear algebra, sorry.) However, I finally got it running.
My sample code testQWidget-Zoom.cc
:
and these three lines are the actual interesting ones (in Canvas::wheelEvent()
):
And this is how it looks:
The first image is a snapshot of the application just after starting it.
Then I pointed into the center of the red rectangle and turned the wheel slightly. The red rectangle grew around the mouse pointer as intended.
1st Update:
And, this is the updated version which uses screen coordinates directly (instead of converting everything to NDCs):
The relevant three lines didn't change much – the mouse coordinates are applied directly to transformation.
Btw. I changed the rendering – it now scales line width as well as I used
in Canvas::paintEvent()
instead of transforming all points "manually".
The snapshot shows the application after I pointed into the center of the blue rectangle and turned the mouse wheel:
2nd Update:
The suggested matrix manipulation works in a QGraphicsView
as well:
Using a QGraphicsView
simplifies code as no rendering code is needed – it's already built-in.
As I have not (yet) much experience with QGraphicsView
, another issue hit me quite hard: The QGraphicsView
is able to fix the view position automati[cg]ally after a transformation has been applied. In my case, this was rather counter-productive as obviously my transformation and the QGraphicsView
seemed to "pull" in opposite directions.
Hence, I've learnt my lesson of the day: QGrapicsView::setTransformationAnchor(QGraphicsView::NoAnchor)
is necessary to switch off this (in my case not-intended) auto-centering.
The other detail I find worth to notice is QGraphicsView::mapToScene()
which can be used to conveniently convert widget coordinates (e.g. mouse coordinates) to scene space.
这篇关于使用 Qt 的缩放功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!