SPlatten
SPlatten

Reputation: 5760

Qt QMessageBox center 'critical' in desktop

The critical method of QMessageBox has 4 overridden methods, it also has individual methods for setting the title, message text and parent.

I want to display a critical error dialog in the center of the desktop. I have the desktop geometry, what I need is the geometry of the message box so I can apply it to the desktop geometry to center the error dialog.

But its a chicken and egg, I can't get the error dialog before it's rendered for positioning, so how do I do this? I don't want to have to resort to magic numbers to apply an offset.

Upvotes: 0

Views: 4708

Answers (2)

Gabriella Giordano
Gabriella Giordano

Reputation: 1238

This should center the dialog on the primary desktop, but I did not test it on multiple screen setup.

 QMessageBox message(QMessageBox::Critical, QObject::tr("Error!"),
                     QObject::tr("This is a critical error!"),
                     QMessageBox::Ok,
                     QApplication::desktop()); 
 message.exec();

EDIT It is indeed one of the constructors of QMessageBox, as user Scheff correctly pointed out. This solution exploits Qt's default behavior of centering dialogs w.r.t. the parent widget.

Sometimes, I found that on some platforms, providing a null parent will not center a dialog on the screen because different window decorators may adopt different policies for dialog positioning. Forcing the desktop widget to be the parent fixed the issue 100% of the times for me.

Anyway, whatever works is good :)

Upvotes: -1

SPlatten
SPlatten

Reputation: 5760

The actual solution was a lot simpler, just removing the parent parameter from the call to critical has the exact desired effect:

    const QString csMsg("\'" + strConfig + "\' does not exist!");
    const QString csTitle("Error");
    QMessageBox msgBox;
    msgBox.critical(nullptr, csTitle, csMsg);
    QApplication::quit();

Upvotes: 1

Related Questions