简体   繁体   中英

Scrolling in QGraphicsView

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM