qt 重写继承QGraphicsView,显示图像二次自适应
时间: 2023-05-15 08:06:34 浏览: 68
您可以通过重写QGraphicsView的resizeEvent()函数来实现图像的二次自适应。在该函数中,您可以重新计算图像的大小和位置,并将其重新设置为视图的场景。具体实现可以参考以下代码:
void MyGraphicsView::resizeEvent(QResizeEvent *event)
{
QGraphicsView::resizeEvent(event);
if (scene() != nullptr) {
QRectF sceneRect = scene()->itemsBoundingRect();
fitInView(sceneRect, Qt::KeepAspectRatio);
}
}
这段代码会在视图大小改变时重新计算场景的大小,并将其自适应地缩放到视图中。
相关问题
qt 重写继承QGraphicsView,显示图像自适应
您可以通过重写QGraphicsView的resizeEvent()函数来实现图像自适应。在resizeEvent()函数中,您可以重新计算图像的大小和位置,并将其设置为视图的大小。以下是一个示例代码片段:
void MyGraphicsView::resizeEvent(QResizeEvent *event)
{
QGraphicsView::resizeEvent(event);
if (scene() != nullptr) {
QRectF sceneRect = scene()->itemsBoundingRect();
setSceneRect(sceneRect);
fitInView(sceneRect, Qt::KeepAspectRatio);
}
}
在这个示例中,我们首先调用QGraphicsView的resizeEvent()函数,以确保视图正确地处理大小更改。然后,我们检查场景是否存在。如果存在,我们计算场景的边界矩形,并将其设置为视图的场景矩形。最后,我们使用fitInView()函数将场景自适应地缩放到视图中。
qt c++重写继承QGraphicsView.打开图像显示时自适应
您可以通过重写QGraphicsView的resizeEvent()函数来实现自适应显示图像。在该函数中,您可以获取QGraphicsView的大小并将其设置为场景的大小,然后调用fitInView()函数以确保图像适合视图。
以下是示例代码:
```
class MyGraphicsView : public QGraphicsView {
public:
MyGraphicsView(QWidget *parent = nullptr) : QGraphicsView(parent) {}
protected:
void resizeEvent(QResizeEvent *event) override {
QGraphicsView::resizeEvent(event);
fitInView(scene()->sceneRect(), Qt::KeepAspectRatio);
}
};
```
您可以将此类用作QGraphicsView的子类,并在需要显示图像时使用它来替换默认的QGraphicsView。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)