Programmatic QGraphicsView scrolling not updating properly

后端 未结 3 597
北海茫月
北海茫月 2021-01-12 19:20

I have a custom class derived from QGraphicsView that implements a slot call scrollHorizontal(int dx), inside the code is simply

void CustomView::scrollHoriz         


        
3条回答
  •  梦谈多话
    2021-01-12 19:37

    Did you try to use the scroll bars? Hiding them doesn't make them non-existent, and the documentation says you should use QScrollBar::setValue to scroll to a given position.

    Another option would be to use QGraphicsView::centerOn(QPointF) in conjunction with the current center point -- as you've also tried -- but directly calculating the center point within your method (do not precalculate and store the center point), by using QGraphicsView::mapToScene(int,int):

    void CustomView::horizontalScroll(int dx)
    {
        QPointF viewCenter = mapToScene(width() / 2, height() / 2);
        viewCenter += QPointF(dx, 0); // Why did you subtract instead of add dx?
        centerOn(viewCenter); // BTW, you don't need to do .x(), .y()
        // You can remove update(); as this is already called in centerOn().
    }
    

    Please note that if you have, as you said, "scrollContentsBy(int dx, int dy) overrided to emit horizontalScroll(dx)", you also have to call the super class method so that the view can scroll itself:

    void CustomView::scrollContentsBy(int dx, int dy)
    {
        emit horizontalScrolled(dx); // (You should call it different than the slot!)
        QGraphicsView::scrollContentsBy(dx, dy); // <-- This is what I mean!
    }
    

提交回复
热议问题