Нужно просто перед центровкой вызвать QWidget::adjustSize(), чтобы отработала компановка.
Вот, имхо, более правильный код:
C++ (Qt)
#include <QApplication>
#include <QDesktopWidget>
void CenterWindow( QWidget* win )
{
QWidget* w = win->parentWidget();
win->adjustSize();
// need to make sure these events are already sent to be sure
// our information below is correct
QApplication::sendPostedEvents( win, QEvent::LayoutHint );
QApplication::sendPostedEvents( win, QEvent::Resize );
QPoint p( 0, 0 );
int extraw = 0, extrah = 0, scrn = 0;
if ( w )
w = w->topLevelWidget();
QRect desk;
if ( w )
scrn = QApplication::desktop()->screenNumber( w );
else if ( QApplication::desktop()->isVirtualDesktop() )
scrn = QApplication::desktop()->screenNumber( QCursor::pos() );
else
scrn = QApplication::desktop()->screenNumber( win );
desk = QApplication::desktop()->availableGeometry( scrn );
QWidgetList wl( QApplication::topLevelWidgets() );
for( QWidgetList::iterator it = wl.begin();
( extraw == 0 || extrah == 0 ) && it != wl.end(); ++it )
{
int framew, frameh;
QWidget* current = *it;
if ( ! current->isVisible() )
continue;
framew = current->geometry().x() - current->x();
frameh = current->geometry().y() - current->y();
extraw = QMAX( extraw, framew );
extrah = QMAX( extrah, frameh );
}
// sanity check for decoration frames. With embedding, we
// might get extraordinary values
if ( extraw == 0 || extrah == 0 || extraw >= 10 || extrah >= 40 )
{
extrah = 40;
extraw = 10;
}
#ifndef Q_OS_TEMP
if ( w )
{
// Use mapToGlobal rather than geometry() in case w might
// be embedded in another application
QPoint pp = w->mapToGlobal( QPoint( 0, 0) );
p = QPoint( pp.x() + w->width() / 2, pp.y() + w->height() / 2 );
} else
{
// p = middle of the desktop
p = QPoint( desk.x() + desk.width() / 2, desk.y() + desk.height() / 2 );
}
#else
p = QPoint( desk.x() + desk.width() / 2, desk.y() + desk.height() / 2 );
#endif
// p = origin of this
p = QPoint( p.x() - dlg->width() / 2 - extraw,
p.y() - dlg->height() / 2 - extrah );
if ( p.x() + extraw + dlg->width() > desk.x() + desk.width() )
p.setX( desk.x() + desk.width() - dlg->width() - extraw );
if ( p.x() < desk.x() )
p.setX( desk.x() );
if ( p.y() + extrah + dlg->height() > desk.y() + desk.height() )
p.setY( desk.y() + desk.height() - dlg->height() - extrah );
if ( p.y() < desk.y() )
p.setY( desk.y() );
win->move( p );
}