您案例中的问题是,布局只会在小部件可见后更新其大小,一种可能的解决方案是通过调用该方法强制它
adjustSize()
的
QDialog
.
有几种方法可以使小部件居中:
-
第一种形式:
QDialog splash;
QVBoxLayout *laySplash = new QVBoxLayout(&splash);
QLabel *lblText = new QLabel;
laySplash->addWidget(lblText);
lblText->setText("hello world! hello world! hello world! hello world! hello world! ");
splash.adjustSize();
splash.setGeometry(
QStyle::alignedRect(
Qt::LeftToRight,
Qt::AlignCenter,
splash.size(),
qApp->desktop()->availableGeometry()
)
);
splash.exec();
-
第二种形式:
QDialog splash;
QVBoxLayout *laySplash = new QVBoxLayout(&splash);
QLabel *lblText = new QLabel;
laySplash->addWidget(lblText);
lblText->setText("hello world! hello world! hello world! hello world! hello world! ");
splash.adjustSize();
QPoint p = QApplication::desktop()->geometry().center()-splash.rect().center();
splash.move(p);
splash.exec();
-
第三种形式(您的方法):
QDialog splash;
QVBoxLayout *laySplash = new QVBoxLayout(&splash);
QLabel *lblText = new QLabel;
laySplash->addWidget(lblText);
lblText->setText("hello world! hello world! hello world! hello world! hello world! ");
splash.adjustSize();
int intScreenHeight = QApplication::desktop()->screenGeometry().height();
int intScreenWidth = QApplication::desktop()->screenGeometry().width();
int intSplashLeft = (intScreenWidth / 2) - (splash.width() / 2);
int intSplashTop = (intScreenHeight /2) - (splash.height() / 2);
splash.move(intSplashLeft, intSplashTop);
splash.exec();