获取 QGraphicsView 的可见矩形?
我已经用这个把头发拔了好几个小时了。有一个线程 这里 关于它,但似乎没有任何效果。 QGraphicsView::rect() 将返回宽度和高度,但 left
和 top
值未正确设置(始终为 0 - 忽略滚动量)。我希望它处于场景坐标中,但它应该很容易从任何系统进行转换。我不知道 horizontalScrollBar()->value()
和 vert 返回什么......似乎是毫无意义的胡言乱语。
// created here
void EditorWindow::createScene() {
m_scene = new EditorScene(this);
m_view = new EditorView(m_scene);
setCentralWidget(m_view);
connect(m_scene, SIGNAL(mousePosChanged(QPointF)), this, SLOT(mousePosChanged(QPointF)));
}
/// with this constructor
EditorView::EditorView(QGraphicsScene* scene, QWidget* parent) : QGraphicsView(scene, parent) {
setRenderHint(QPainter::Antialiasing);
setCacheMode(QGraphicsView::CacheBackground);
setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
setDragMode(QGraphicsView::NoDrag);
scale(1.0, -1.0); // flip coordinate system so that y increases upwards
fitInView(-5, -5, 10, 10, Qt::KeepAspectRatio);
setInteractive(true);
setBackgroundBrush(QBrush(QColor(232,232,232), Qt::DiagCrossPattern));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
只需使用视图将基于像素的视口矩形映射到场景即可:
再见,
马塞尔
Just map the pixel-based viewport rectangle to the scene using the view:
Bye,
Marcel
没关系。想出了这个,这似乎有效。
Nevermind. Came up with this, which seems to work.
以下实现为我返回了最好的结果:
当出现滚动条时,它仍然非常有效。仅当视图不显示旋转或剪切的场景时,此功能才能正常工作。如果视图被旋转或剪切,则可见矩形在场景坐标系中与轴不平行。在这种情况下,
返回一个
QPolygonF
(不是QRectF
),它是场景坐标中的可见矩形。顺便说一句,QPolygonF
有一个成员函数boundingRect()
,它不会返回视图的正确可见矩形,但无论如何可能很有用。The following implementation returned the best results for me:
This works still really well when scrollbars appear. This only works properly if the view does not display the scene rotated or sheared. If the view is rotated or sheared, then the visible rectangle is not axis parallel in the scene coordinate system. In this case
returns a
QPolygonF
(NOT aQRectF
) which is the visible rectangle in scene coordinates. By the way,QPolygonF
has a member functionboundingRect()
which does not return the properly visible rectangle of the view, but might be useful anyways.您可以执行您已完成的操作,或使用 mapToScene() 函数。但是,您不能指望生成的场景“矩形”是矩形,因为场景可能在视图中旋转或剪切,从而在映射到场景时产生一般多边形。
当然,如果您的应用程序从不执行此类操作,您可以随意假设矩形始终合适。
You can do what you've done, or use the mapToScene() functions. You can't count on the resulting scene "rectangle" being a rectangle, however, because the scene might be rotated or sheared in the view, resulting in a general polygon when mapped to the scene.
If your application never does such things, of course, you're free to assume that a rectangle is always appropriate.
@mpen 的 Qt5/Qt6 版本解决方案:
Qt5/Qt6 version of the solution by @mpen:
听起来你想要的是场景矩形。
::rect()
方法继承自QWidget
。请参阅:http://doc.qt.io/qt-5/ qgraphicsview.html#sceneRect-prop
It sounds like what you want is the scene rectangle. The
::rect()
method is inherited fromQWidget
. See:http://doc.qt.io/qt-5/qgraphicsview.html#sceneRect-prop