PDA

View Full Version : QGraphicsView::centerOn not working in QMainWindow's constructor



wayfaerer
13th March 2012, 01:46
In my main window's constructor I create a QGraphicsScene and View, set the scene to the view, add the QGraphicsView to the main window's layout, and then call QGraphicsView::centerOn(0,0), so that the QGraphicsView will show the scene in the middle of the view. However, it would display the scene offset by some weird amount, rather than in the middle like I want it to.

I've heard about some general funk relating to QGraphicsView and having to call it's methods *after* it's drawn onto the screen. Well, that didn't really help, because I was calling QGraphicsView::centerOn(0,0) at the very end of my main window's constructor... so I didn't see how to call it after that, unless I set up a timer or something stupid like that.

But then I had the idea to re-implement QMainWindow::showEvent, and call QGraphicsView::centerOn(0,0) in there, rather than in the constructor. What do you know... that fixed it!

My question is: Why does this happen? Am I missing something?

ChrisW67
13th March 2012, 04:26
Constructing a QMainWindow object and displaying the window that object represents are two different things. At the very end of the constructor the main window is not visible.

What size does the undisplayed graphic view have in the undisplayed main window when you ask it to centre the view? When the main window is displayed and gets a concrete size so does the graphics view. How do you expect the graphics view content to move during this resize? Do you expect it to keep the same centre when it is resized during first display, but not when manually resized? The scroll bar granularity can also have an impact.

It's three lines of code to ensure the scene is centred on first showing:


MainWindow(...) {
...

QTimer::singleShot(0, this, SLOT(centreOnFirstDisplay()));
}

public slots:
void centreOnFirstDisplay() { view->centerOn(0, 0); }

wayfaerer
13th March 2012, 05:26
Very helpful. Thank you!