Important: Please read the Qt Code of Conduct -

Can't Get position of the window

  • Hello
    I am new to Qt
    I have written a simple application and I want to get current position of the QMainWindow.
    this is my code:

    M::M(QWidget *parent) :
    ui(new Ui::M)
    QMessageBox msg;
    msg.setText(QString::number("what returns the X or Y of the window?"));

    I searched a lot. There where topics about setting the position, not getting it.
    I also tried geometry().x(), but it always returns 0 !!!
    Please help me. I need this.
    Best regards...

  • @erfan


    I didn't test this on my end, so it might not work. This is what I recommend:

    Call geometry.x() after you called the show() function for your window widget. The reason why I recommend this is because recently, I was
    not getting the correct button size until I requested it after I showed the window. When I called it before hand, it gave me answers that I knew were incorrect. Also, looking at your code, I don't see where you called a window's widget so that it can be displayed and with the embedded QMessageBox on that widget.

  • Not tested, but the doc seems to say that it provides what you want.

  • @erfan Just to be more clear on what you want..

    When you say current position, current position in where?

    Meaning, In your desktop do you want to know where your UI is? Or, Inside the window, where the widgets are present?


  • Moderators

    You can't get a position of your window inside that window's constructor because it doesn't have one yet.
    The window manager of your OS gives your window a position when it is first shown (or if you explicitly called move() before).
    The window is shown when you call on it show()or any of the related functions like showMaximized().

    After the window is shown you can get the window position including window frame with pos() and without the window frame with geometry().topLeft().

Log in to reply