Search code examples
c++qtqt4qt5qmessagebox

Messagebox not closing while closing parent for calling Hide or close explicitly


I have QMessageBox as member to a widget class If the messagebox is kept open and through program if we close widget messagebox is not getting closed. I did setParent also for message box

// Code local to a function
reply = m_warningMsg.question(this,"Warning","Do you really want to close the connection",QMessageBox::Yes | QMessageBox::No);
if(reply == QMessageBox::No)
{
    return;
}

//Function to close the widget
void Window::closeConnection()
{
    m_warningMsg.setParent(this);
    m_warningMsg.setVisible(true);

    // Code inside if executed but not hiding messagebox
    if(m_warningMsg.isVisible())
    {
        m_warningMsg.close();
        m_warningMsg.hide();
    }
    close();
}

Solution

  • QMessageBox::question() is a static method so m_warningMsg is not the QMessageBox that is displayed, as you have passed as a parameter to this as a parent then we can find that QMessageBox (note that it is not necessary to use m_warningMsg) using findchild():

    QMessageBox::StandardButton reply = QMessageBox::question(this,"Warning","Do you really want to close the connection",QMessageBox::Yes | QMessageBox::No);
    if(reply == QMessageBox::No)
    {
        return;
    }
    

    void Window::closeConnection()
    {
        QMessageBox *mbox = findChild<QMessageBox*>();
        if(mbox)
            mbox->close();
        close();
    }