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

↘锁芯ラ 提交于 2019-12-23 11:55:27

问题


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);
    }
}

回答1:


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




回答2:


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




回答3:


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);
    }
}


来源:https://stackoverflow.com/questions/21635427/how-to-set-qdialog-width-and-height-and-allow-automatic-window-placement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!