Qt QGraphicsScene::setSceneRect() 实际上并没有设置场景矩形
Qt QGraphicsScene::setSceneRect() doesn't actually set the scene rect
我已经实现了一个简单的图像查看器小部件。它工作正常,但是当我尝试上传图片然后用较小的图片替换它时,它没有居中。我做了一些小研究,发现问题出在 QGraphicsScene
中的 sceneRect
。所以我写了一些代码来在每次上传图像之前重置它。我还在两行之间添加了一些 qDebug()
内容,以确保它确实将此 rect 设置为 null。不幸的是,即使在调用此 setSceneRect()
函数后它仍然保持不变。这里有一些代码可以更好地理解我的问题:
void function_which_uploads_and_show_images()
{
QString file_path = QFileDialog::getOpenFileName(this, "title", "/", "*.jpg");
this->image = QPixmap(file_path);
this->scene->clear();
this->scene->setSceneRect(QRectF()); //setting sceneRect to the null rect
// here goes some code to scale the image if necessary
this->scene->addPixmap(file_path);
}
我的问题是:如何重置 sceneRect
以便每次上传图片时它都居中?
首先,您只是提供了关于图像如何真正居中的部分代码 "automagically"。您可能需要查看类似 QGraphicsLayout
的内容来管理定位。
但要解决这个问题,您可以尝试在 视图 上设置场景矩形。您可能只需要在初始时间执行一次。
来自 QGraphicsView::sceneRect
文档:
The scene rectangle defines the extent of the scene, and in the view's case, this means the area of the scene that you can navigate using the scroll bars.
If unset, or if a null QRectF is set, this property has the same value as QGraphicsScene::sceneRect, and it changes with QGraphicsScene::sceneRect. Otherwise, the view's scene rect is unaffected by the scene.
By default, this property contains a rectangle at the origin with zero width and height.
也许这不是解决这个问题的一个非常干净的解决方案,但可以执行以下操作来重置场景矩形:
scene = new QGraphicsScene(this);
view->addScene(scene);
它有效,但我几乎可以肯定它可以通过其他方式实现,所以如果您对此问题有更好的答案,请post在这里。
我已经实现了一个简单的图像查看器小部件。它工作正常,但是当我尝试上传图片然后用较小的图片替换它时,它没有居中。我做了一些小研究,发现问题出在 QGraphicsScene
中的 sceneRect
。所以我写了一些代码来在每次上传图像之前重置它。我还在两行之间添加了一些 qDebug()
内容,以确保它确实将此 rect 设置为 null。不幸的是,即使在调用此 setSceneRect()
函数后它仍然保持不变。这里有一些代码可以更好地理解我的问题:
void function_which_uploads_and_show_images()
{
QString file_path = QFileDialog::getOpenFileName(this, "title", "/", "*.jpg");
this->image = QPixmap(file_path);
this->scene->clear();
this->scene->setSceneRect(QRectF()); //setting sceneRect to the null rect
// here goes some code to scale the image if necessary
this->scene->addPixmap(file_path);
}
我的问题是:如何重置 sceneRect
以便每次上传图片时它都居中?
首先,您只是提供了关于图像如何真正居中的部分代码 "automagically"。您可能需要查看类似 QGraphicsLayout
的内容来管理定位。
但要解决这个问题,您可以尝试在 视图 上设置场景矩形。您可能只需要在初始时间执行一次。
来自 QGraphicsView::sceneRect
文档:
The scene rectangle defines the extent of the scene, and in the view's case, this means the area of the scene that you can navigate using the scroll bars.
If unset, or if a null QRectF is set, this property has the same value as QGraphicsScene::sceneRect, and it changes with QGraphicsScene::sceneRect. Otherwise, the view's scene rect is unaffected by the scene.
By default, this property contains a rectangle at the origin with zero width and height.
也许这不是解决这个问题的一个非常干净的解决方案,但可以执行以下操作来重置场景矩形:
scene = new QGraphicsScene(this);
view->addScene(scene);
它有效,但我几乎可以肯定它可以通过其他方式实现,所以如果您对此问题有更好的答案,请post在这里。