如何改进这段代码,使图片随着graphicsview控件大小而变换大小
时间: 2024-03-17 20:43:57 浏览: 21
可以通过监听graphicsview的大小变化来动态调整图片的大小,可以参考如下代码:
```c++
// 创建图片对象
QPixmap qImgSrc = QPixmap::fromImage(QImage(imgsrc.data, imgsrc.cols, imgsrc.rows, QImage::Format_RGB888));
QPixmap qImgBin = QPixmap::fromImage(QImage(imgthreshold.data, imgthreshold.cols, imgthreshold.rows, QImage::Format_RGB888));
// 创建场景对象
QGraphicsScene scene1, scene2;
// 创建图片项并添加到场景中
QGraphicsPixmapItem item1(qImgSrc);
QGraphicsPixmapItem item2(qImgBin);
scene1.addItem(&item1);
scene2.addItem(&item2);
// 设置场景
ui.graphSrc->setScene(&scene1);
ui.graphBin->setScene(&scene2);
// 监听graphicsview大小变化
connect(ui.graphSrc, &QGraphicsView::resized, [&](){
item1.setPixmap(qImgSrc.scaled(ui.graphSrc->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
});
connect(ui.graphBin, &QGraphicsView::resized, [&](){
item2.setPixmap(qImgBin.scaled(ui.graphBin->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
});
```
上述代码中,使用`connect`函数监听了`QGraphicsView`的`resized`信号,即大小变化事件。当控件大小变化时,调用`setPixmap`函数重新设置图片项的大小,使其与控件大小保持一致,并保持图片的长宽比例不变。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)