Qt World Summit: Register Today!

[solved] Center QWidget in QLayout

  • I have a QGraphicsView in a QVBoxLayout (the only item) and that layout is set to the central widget of a QMainWindow. The QGraphicsView is set to a fixed size and is smaller than the QMainWindow. The layout is doing it's magic fine and the QGraphicsView is perfectly centered. [Image 1]

    So far so good. Now I do a resize() event on the QGraphicsView. The widget is being resized correctly but now it sticks to the upper left corner of the layout. [Image 2]

    How can I fix this? I want the QGraphicsView widget to be centered as in the initial state all the time.

    Image 1: http://paste.ugfx.org/sores/99d72c7fc3e2/d756da7972c2.jpg
    Image 2: http://paste.ugfx.org/sores/99d72c7fc3e2/ef133f1d6c08.jpg

    ~ Tectu

  • Moderators

    Can you post the code that sets the layout, adds the widget to the layout, sets the fixed size and calls resize? My guess is that you don't set a layout or the central widget properly or the graphics view somehow becomes layoutless (if that's even a word).

    When adding the widget make sure you pass Qt::AlignCenter to the addWidget() call of the layout.
    If you set the size using setFixedSize() then resize() won't work. You can call setFixedSize() again.

  • Thank you very much for your quick answer. Here's the related code:

    MainWindow: http://paste.ugfx.org/show/e7834cb915
    MyGraphicsView: http://paste.ugfx.org/show/e4a74afb40

    I did layout->setAlignment(Qt::AlignCenter) before but then just the upper left corner of the widget is at the center of the layout. What I actually need is that the center of the widget is at the center of the layout.

  • Moderators

    bq. I did layout->setAlignment(Qt::AlignCenter) before

    This sets the alignment of the layout, not the widget inside it. Instead set the alignment when you add the widget to the layout:
    layout->addWidget(_activeDisplayPageView, 0, Qt::AlignCenter);

    Also setFixedSize() is basically calling setMinimumSize and setMaximumSize with the same value so you can replace this:
    setMinimumSize(QSize( 10, 10));
    setMaximumSize(QSize(10000, 10000));
    with this:

  • Using setFixedSize() instead of what I did fixed the problem!

    Thank you very much for your help. I appreciate it a lot!

Log in to reply