1
votes

I know that QDialog's are supposed to default to being positioned centered on the parent window but I'm apparently missing some subtlety. I have an object, derived from QWidget, and am trying to create a child dialog centered on that using the following test code

QDialog *dialog = new QDialog(this);
QPoint dialogPos = dialog->mapToGlobal(dialog->pos());
QPoint thisPos = mapToGlobal(this->pos());
dialog->exec();

When I do this, the dialog is showing up in the top left corner of my window. dialogPos is (0,0) and thisPos is (808, 371).

What am I missing? Why is the dialog not showing up centered as I would expect?

2
Have you tried to do something like this: stackoverflow.com/a/18302990/867349 ? - tro
That is for QWidget. My understanding is that for QDialog it should be done automatically. - ryan0270

2 Answers

6
votes

How to center QDialog to it`s parent QWidget

void Dialog::showEvent( QShowEvent* )
{
    QRect parentRect( parentWidget()->mapToGlobal( QPoint( 0, 0 ) ), 
parentWidget()->size() );
    move( QStyle::alignedRect( Qt::LeftToRight, Qt::AlignCenter, size(), 
parentRect ).topLeft() );
}
1
votes

I subclassed a QDialog and put the following code in the constructor.

QPoint dialogCenter = mapToGlobal(rect().center());
QPoint parentWindowCenter = parent->window()->mapToGlobal(
    parent->window()->rect().center());
move(parentWindowCenter - dialogCenter);

After that the dialog was centered over the parent window. My system is running Qt5.3.1 and Ubuntu 14.04.