Nominate our 2022 Qt Champions!

[SOLVED] Moving widget to the window center

  • Hi.
    I'm trying to move QLabel with setted QMovie in it in the center of my main window.
    But after QLabel moving QMovie is not displayed on the screen. Where I have mistaken and what are other ways of solving this problem?
    @ui->label->move( ui->label->parentWidget()->geometry().center());@

  • Have not tested but you can try this:

  • I tried your variant but label's position is not in the center after execution of that code, it's position in my case is in lower right corner.

  • Well, I need to understand what you really want and it is difficult with just one line of code. I need to see a little more.


  • Ok, here is all programm's code:
    @MainWindow::MainWindow(QWidget *parent) :
    ui(new Ui::MainWindow)
    this->setFixedSize(200, 200);

    delete ui;
    And the result:

  • Moderators

    The code you both presented doesn't move the label to the center. It moves the label so that the upper left corner of it is in the center, which might mean that the label itself lands in the corner if it's big enough. To properly center it you need to take under consideration the fact that label has width and height i.e. you need to subtract half of it from the center to position it correctly.

    Another thing is that you take whatever->geometry().center() which is actually the center point of the whatever in the parent coordinates, which is garbage for the label. The center of label parent would be label->parentWidget()->rect().center(). In your case it would be just rect()->center() since you're in the main window constructor.

    Mix those two things and you'll be ok.
    Or... just use a layout and don't think about coordinates anymore.

  • Yes, thats right. The easiest way is a layout. Or you need to make some calculations to center it.

  • I just want to have something like little loading circle. For that purpose I selected label and setted QMovie in it. Now I want to move it to the center of form. Maybe it is better decision to invoke another single window with label on it?

  • But question remain alive ?? how can you bring another single window in the center?? If u can do that.. than you can bring label in the center.

    Well, I am totally agree with chris kawa. He is absolutely right.
    why don't u try some kind of calculation to bring label in perfect center ??

  • You can try this

    ui->label->move(window.width() / 2 - ui->label.width() / 2, window.height() / 2 - ui->label.height() / 2);


  • Thanks for all comments: I did like you said and just calculated the center of the form.

Log in to reply