Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set QDialog width and height and allow automatic window placement

Tags:

qt

qdialog

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);
    }
}
like image 452
Alex Avatar asked Feb 07 '14 18:02

Alex


2 Answers

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);
    }
}
like image 106
Alex Avatar answered Sep 23 '22 16:09

Alex


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

like image 44
Zlatomir Avatar answered Sep 20 '22 16:09

Zlatomir