简体   繁体   中英

Setting parent for a QMessageBox

i can't understand what's the benefit of setting parent for a QMessageBox , for instance in the following code:

void mainWindow::showMessage(QString msg) {
  QMesageBox::information(this, "title", msg); //'this' is parent
}

can somebody help me?

Probably a few things. First of all QMessageBox inherits from QDialog . Since QDialog has a concept of a parent, QMessageBox should too for consistency.

Specifically, the documentation says:

parent is passed to the QDialog constructor.

At the very least, a new dialog is often displayed centered in top of its parent.

However, there is more!

According to the documentation it can effect actually functionality. For example:

On Mac OS X, if you want your message box to appear as a Qt::Sheet of its parent , set the message box's window modality to Qt::WindowModal or use open(). Otherwise, the message box will be a standard dialog.

Also, there is a concept of both "Window Modality" and "Application Modality", where the former only prevents input in the parent window, the latter prevents input for the whole application. This obviously requires the concept of a parent to be known.

Finally, for certain static functions such as ::about(...) , the first place it looks for an icon to use is parent->icon() .

So, if you want to get nice platform specific behavior and have your code be cross platform, you are better off passing a sane parent to it.

The parent-child hierarchy of dialogs defines the window stacking behavior in the various platforms. If you pass dialog P as parent of dialog C, C will appear above P on all (desktop) platforms. If you pass 0, the window stacking will differ and usually not behave as wanted. The worst such issues I've seen on OS X, where some message boxes showed up behind the main window, which was disabled as the message boxes being modal, without any way to get to the message box (neither shortcuts nor moving windows via mouse helped). In short, my suggestion: always pass a sensible parent.

The other answers are probably better, but my own little reason is that it puts the message box at the centre of the parent instead of the centre of the screen...

Don't forget to mention that QMessageBox will inherit of the palette and the style-sheets of its parent. Believe me when you use custom complex style-sheets you don't want you message to pop like they doesn't belong to your application...

It is also useful for memory management if you don't use static functions, but actually create an instance of QMessageBox. When the parent is deleted your instance will be deleted too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM