QGraphicsView不适合Qt中的窗口



我有QGraphicsView,它有多个QGraphicsItem。当我的视图第一次加载并在屏幕上可见时,它无法完全适应屏幕。大约80%的视图可见。然后我需要使用滚动来查看视图的剩余20%。

加载时如何显示我的整个视图?

我尝试了以下方法:
(将所有项目添加到视图中后(

QRectF a = scene->sceneRect();      
view->ensureVisible(a,200,200);        

但我的观点仍然是80%可见的。

首先,关闭滚动条,可以通过以下方式实现:

setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

在CCD_ 1实例上调用。

如果已将所有添加的项目添加到场景中,请使用sceneRef获取所有添加到场景的项目的bouding rect,并通过viewport()方法访问视图的视图可绘制小部件的几何体。

当您有场景几何体和视图几何体时,您可以计算比例因子,该比例因子可以通过QGraphicsView::scale()方法应用于视图。

计算比例因子的算法(垂直轴和水平轴都有一个比例因子,因为我们不想在某些轴上拉伸视图内容(如下:

if (sceneWidth > viewWidth)
s = viewWidth / sceneWidth
// check if scene scaled by scale fit in vertical
if (s * sceneHeight > viewHeight)
s = viewHeight / sceneHeight
// else if condition for checking sceneHeight > viewHeight
view->scale(s,s)

最小代码:

class TRect : public QGraphicsItem
{
public:
TRect(QGraphicsItem* parent = nullptr) : QGraphicsItem(parent) {}
QRectF boundingRect() const override { return QRectF(0,0,20,20); }
void paint(QPainter *painter, const QStyleOptionGraphicsItem*, QWidget*) override {
painter->fillRect(QRectF(0,0,20,20), QColor(255,255,0));
}
};
class TView : public QGraphicsView {
public:
TView(QWidget* parent) : QGraphicsView(parent) {}
void resizeEvent(QResizeEvent *e) noexcept override {
QGraphicsView::resizeEvent(e);
QRectF rc = scene()->sceneRect();
float s = 1.0f;
if (rc.width() > viewport()->width()) {
s = (float)viewport()->width() / rc.width();
float newHeight = s * rc.height();
if (newHeight > viewport()->height())
s = (float)viewport()->height() / rc.height();
}
else if (rc.height() > viewport()->height()) {
s = (float)viewport()->height() / rc.height();
float newWidth = s * rc.width();
if (newWidth > viewport()->width())
s = (float)viewport()->width() / rc.width();
}
this->scale(s,s);
}
};
class TMainWindow : public QWidget  {
TView* _view = nullptr;
QGraphicsScene* _scene = nullptr;
public:
TMainWindow() {
QVBoxLayout* layout = new QVBoxLayout(this);
_view = new TView(this);
_view->setFixedSize(300,400);
_scene = new QGraphicsScene(this);
_view->setScene(_scene);
_view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
_view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
for (int i = 0; i < 10; ++i)
{
TRect* rc = new TRect();
rc->setPos(i*100,i*100);
_scene->addItem(rc);
}        
layout->addWidget(_view);
}
};

TView::resizeEvent中包含的代码可以放在函数中,并在需要时调用它:

  • 向场景添加/删除项目
  • 更改了视图大小

最新更新