1
votes

I have problem with scrolling in QGraphicsView.

I've set scene rect in my QGraphicsView subclass:

MyQGraphicsView::MyQGraphicsView{
    setSceneRect(0,0,2000,2000)
}

And overloaded paintEvent:

void MyQGraphicsView::paintEvent(QPaintEvent *event){
    qDebug()<<"Paint event";
    QPainter painter(viewport());
    painter.setRenderHint(QPainter::Antialiasing);
    paint(painter);
}
void MyQGraphicsView::paint(QPainter &painter){
    painter.setPen(Qt::NoPen);
    painter.fillRect(QRect(0,0,200,200),Qt::gray);
    painter.fillRect(QRect(500,500,1000,100),Qt::green);
    painter.setPen(QPen(Qt::white,4,Qt::DashLine));
    painter.drawLine(QLine(0,35,200,35));
    painter.drawLine(QLine(0,165,200,165));
}

When I scroll the second rectangle is not visible. When I resize window it is. Also when scrolling rectangle is extending in wired way.

How should scrolling be implemened in this case? I've found several topics about scrolling in QGraphicsView but none solves my problem.

1

1 Answers

2
votes

QGraphicsView inherits QAbstractScrollArea. So its content is displayed in its internal widget that can be obtained using viewport(). If you want to paint something and be able to scroll it, you need to attach an event filter to viewport widget and process its paintEvent, not view's event.

But you should not do this for QGraphicsView. You're trying to do something terribly wrong. You should not reimplement QGraphicsView::paintEvent just to paint something! It totally devalues its advantages. You need to use QGraphicsScene to add something to the view.