9

Is there a way to just initialize a QDialog's width and height and not change the x and y coordinates without using a ui file? I just have a simple QDialog and want to set only the width and height, and have the x and y automatically set to the center of the parent, but when I try setGeometry, the inherited geometry's x and y are 0. How does the x and y get set when the dialog is created using a ui file?

class MyDialog : public QDialog
{
    MyDialog::MyDialog(QWidget *parent) :
        QDialog(parent)
    {
        setGeometry(geometry().x(), geometry().y(), 200, 400);
    }
}
Alex
  • 712
  • 2
  • 13
  • 27
  • 1
    Try with resize instead of setGeometry, resize should work as you expected: https://qt-project.org/doc/qt-5/qwidget.html#size-prop – Zlatomir Feb 07 '14 at 18:50
  • ok, that kind of works, but the x and y are not centered based on the new width and height. – Alex Feb 07 '14 at 18:58

3 Answers3

7

I have better solution:

class MyDialog : public QDialog
{
    MyDialog::MyDialog(QWidget *parent) :
        QDialog(parent)
    {
        int nWidth = 300;
        int nHeight = 400;
        if (parent != NULL)
            setGeometry(parent->x() + parent->width()/2 - nWidth/2,
                parent->y() + parent->height()/2 - nHeight/2,
                nWidth, nHeight);
        else
            resize(nWidth, nHeight);
    }
}
Alex
  • 712
  • 2
  • 13
  • 27
5

Use with resize instead of setGeometry, it should work as you expected.

Zlatomir
  • 6,964
  • 3
  • 26
  • 32
  • right, but the dialog now looks like it was opened and someone resized it. it's not centered as it would be if it was created using the ui gui designer – Alex Feb 07 '14 at 19:03
4

I'd like to extend your solution to work also on systems with a second monitor (even if this is an old thread...):

...
if (parent != NULL)
    QPoint parentPos = parent->mapToGlobal(parent->pos());
    setGeometry(parentPos.x() + parent->width()/2 - nWidth/2,
                parentPos.y() + parent->height()/2 - nHeight/2,
                nWidth, nHeight);
else
...

Marcel

Marcel
  • 41
  • 3