Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

"this" keyword passed as parent parameter



  • QMessageBox::information(this,"Message","You clicked on that button",QMessageBox::Ok);

    I know that the "this" keyword returns the address of the current object, but I didn't get it in the context above.

    What does the "this" keyword really do in the context above and why it's provided it as its parent?



  • @cs_student

    this is passed to set this (the QWidget you are currently in) as parent of your QMessageBox.
    If you leave it out, which is not possible in your case, your standard QMessageBox ' parent is a nullptr (= no parent).

    It's necessary here because it shows this special type of QMessageBox in relation to your QWidget, that invokes it instead of (parentless) "floating around".
    (EDIT: Instead of passing a valid widget, a nullptr is possible too, like @GrecKo said below, but you can't leave it out)

    So these static MessageBoxes like QMessageBox::information() or QMessageBox::warning() need a parent, while a standard QMessageBox does not.


  • Qt Champions 2018

    It's possible to pass nullptr as a parent.
    The parent here acts only to position the message box relatively to it (on top of it, in the same window).



  • @GrecKo

    But why the QMessageBox standard constructor has nullptr as default value while the static messageBox functions don't?
    (Edit: Never mind... I didn't realized the parameter order)

    Of course you can pass a nullptr, but in your case, you can not just leave it out.


  • Lifetime Qt Champion

    @cs_student said in "this" keyword passed as parent parameter:

    What does the "this" keyword really do in the context above and why it's provided it as its parent?

    Read this: https://doc.qt.io/qt-5/objecttrees.html


Log in to reply