Question

I have this

int MainWindow::messageBox( QString button, QMessageBox::ButtonRole buttons, QString info, QMessageBox::Icon icon )
{
    QFont f;

    f.setPointSize(6);

    QMessageBox *message = new QMessageBox(this);
    message->setWindowModality(Qt::WindowModal);
    message->setFont(f);
    message->setText(info);
    message->addButton( button, buttons );
    message->setWindowTitle("MainWindow");
    message->setIcon(icon);
    message->move( this->width() / 2, this->height() / 2 );

    return message->exec();
}

But I can't make the qmessagebox go to the center of the screen, I also tried using setGeometry, but it doesn't work. Any ideas on this?

Was it helpful?

Solution

I solved using show() before moving it. This is the code:

int MainWindow::messageBox( QString button, QMessageBox::ButtonRole buttons, QString info, QMessageBox::Icon icon )
{
    QFont f;
    QMessageBox *message = new QMessageBox(this);
    QDesktopWidget *win = new QDesktopWidget();

    f.setPointSize(6);

    message->setWindowModality(Qt::WindowModal);
    message->setFont(f);
    message->setText(info);
    message->addButton( button, buttons );
    message->setWindowTitle("MainWindow");
    message->setIcon(icon);
    message->show();
    message->move( win->width() / 2 - message->width() / 2, win->height() / 2 - message->height() / 2 );

    return message->exec();
}

OTHER TIPS

A QMessageBox is created with the window flag Qt::Dialog (and indirectly, Qt::Window). This means that it will be treated like a system window even though it has a parent assigned. When you call move() on it, it will be positioned in desktop coordinates.

When you move the message box in your code above, you are telling it to appear at desktop coordinates equal to half the width and height of your main application window size offset from origin (the top left corner of you desktop).

If your main application window has a size of 400x200, then your message box will appear at desktop coordinates 200,100 no matter where your main application window is located.

If you make your application window full screen and then display the message box, the message box should appear (roughly) at the center of your desktop display. I say roughly because you are specifying the position of the top left corner of the message box, not where the center of the message box will appear to be.

If you want the message box to always appear at the center of the screen, then you need to use the information provided by QDesktopWidget to determine what the correct screen coordinates should be.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top