Search code examples
qtdialogpositionscreen

Position a dynamic QDialog with respect to display/screen size in Qt


I'd like to position and then show a dialog with respect to the display. The dialog has a label. The dialog expands based on the size of the label.

Below is my code that does not work. It tries to show the dialog at the center of the screen (the dialog is shown at the center by default and this code is just for evaluation):

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! ");

int intScreenHeight = QApplication::desktop()->screenGeometry().height();
int intScreenWidth = QApplication::desktop()->screenGeometry().width();

splash.layout()->update();
splash.layout()->activate();

int intSplashLeft = (intScreenWidth / 2) - (splash.width() / 2);
int intSplashTop = (intScreenHeight /2) - (splash.height() / 2);
splash.move(intSplashLeft, intSplashTop);

splash.exec();

What am I doing wrong?

(I am using Qt5 in Linux)


Solution

  • The problem in your case is that the layout will only update the size of the widget after it is visible, a possible solution is to force it by calling the method adjustSize() of the QDialog.

    There are several ways to center a widget:

    1. First form:

    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();
    
    1. Second Form:

    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();
    
    1. Third form(your method):

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