c++ - QGraphicsView适合任何尺寸的图像,没有滚动条

标签 c++ qt qgraphicsview

我的工作环境:Qt 5.8 MSVC2015 64位、QT GraphicsView、QGraphicsObject、Windows 7 64位。

我正在使用 QImage 加载任何尺寸的图像, 尝试适合固定大小(宽度 200 X 高 200)的 QGraphicsView。我不想在 QGraphicsView 中使用滚动条。

在下面的示例中:

  1. 我的 QGraphicsView 尺寸将始终固定为宽度 200 X 高度 200。
  2. 我的图像大小可能会有所不同,但在下面的代码中我的图像 宽182*高174。

那么我如何才能将图像调整到固定大小的 QGraphicsView 中?

 QImage *ImageData;
 QGraphicsView*  _ThumbNailView = new QGraphicsView(this);
_ThumbNailView->setFixedSize(200, 200);  //QGraphicsView will be alwyas constant.
 QGraphicsScene*    _scene =  new QGraphicsScene();
_scene->setSceneRect(0,0,200,200);
 ..........


 myQGraphicsItem* _thumbsquare = new myQGraphicsItem(imageWidth, imageHeight, ImageData);


 //Load image from buffer
    unsigned char *buffer;   ////some image Data get loaded here. 
    int imageWidth = 182;   //I am getting image Width 182, or any size.
    int imageHeight = 174; //I am getting image Height 174 or any size.
    size_t  size = imageWidth * imageHeight * 3;
    int  bytesPerLine = size / imageHeight;
    QImage* _image = new  QImage(reinterpret_cast<const uchar *>(buffer),182, 174, bytesPerLine, QImage::Format_RGB888);
    _thumbsquare->setMyImage(QImage);

...........    

 int width = _ThumbNailView->geometry().width();    // always const 200
 int height = _ThumbNailView->geometry().height(); // always const 200
_ThumbNailView->resize(width, height);
_scene->addItem(_thumbsquare);
_scene->setSceneRect(_scene->itemsBoundingRect());

// This don't work, make image very small
//_ThumbNailView->fitInView(QRectF(0, 0, 200, 200));

以上代码结果

Above Code OutPut

预期的无滚动条的完整图像

Image Without Scroll bar

非常感谢任何建议或帮助?

最佳答案

@ Eligijus,感谢您的帮助,它帮助我找到了解决方案。

我的代码更改:

QRectF bounds = _scene->sceneRect();
QRectF rect  {0,0,200,200};
if (bounds.width() < 200)
{
    rect .setWidth(bounds.width());
    bounds.setWidth(200);
}
if (bounds.height() < 200)
{
    rect.setWidth(bounds.height());
    bounds.setHeight(200);
}
 _ThumbNailView->fitInView(bounds, Qt::KeepAspectRatio);
 QRectF changeRect  = _scene->sceneRect();
_ThumbNailView->updateGeometry();

但是如果图像大小小于200,那么你将面临问题,否则事情会顺利进行。

关于c++ - QGraphicsView适合任何尺寸的图像,没有滚动条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44972450/

相关文章:

c++ - 在此字符串操作代码中出现 out_of_range 错误

c++ - 结构引用编译错误 : expected identifier or ‘(’ before ‘&’ token

c++ - Qt软件调试技巧

c++ - 从 QList<QListWidgetItem *> 到 QStringList 的转换?

c++ - 线程终止后出现 Qt 主窗口

python - 在 QGraphicsView 中显示 X 和 Y 坐标线

c++ - QGraphicsScene 在 QGraphicsView 中奇怪地缩放

c++ - boost 上下文类

c++ - GCC 允许我从空字符串中取消引用迭代器

c++ - QGraphicsItem 边框样式