I have a custom class derived from QGraphicsView that implements a slot call scrollHorizontal(int dx), inside the code is simply
void CustomView::scrollHoriz
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!
}
I've worked with QGraphicsView
in Qt 4.6.3 - 4.7.2 and have to argue that you can use the respective QScrollBar
in the following way:
//graphics view initialization
QGraphicsView *graphicsView = new QGraphicsView(parent);
QGraphicsScene *scene = new QGraphicsScene(0,0,widthOfScene,heightOfScene,parent);
graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
graphicsView->setScene(scene);
//in another method
QScrollBar* yPos=graphicsView->verticalScrollBar();
yPos->setValue((int) newValue);
It does not matter if they are hidden or not. They will still respond to setValue(int)
as long as you have a graphics scene that is larger than the graphics view.
The QGraphicsView
will also respond to ensureVisible
, which moves the scrollbars to the appropriate location.
You are not supposed to call scrollContentsBy
as explained here: http://qt-project.org/doc/qt-4.8/qabstractscrollarea.html#scrollContentsBy
I don't know if you can still call the hidden scrollbar to scroll it. If not, translate is an option.