Setting parent for a QMessageBox

橙三吉。 提交于 2019-12-22 08:33:01

问题


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 ?


回答1:


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.




回答2:


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.




回答3:


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...




回答4:


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 ...




回答5:


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.



来源:https://stackoverflow.com/questions/6754049/setting-parent-for-a-qmessagebox

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!