[solved] Crash while attempting to add QWidget to QDialog via QGridLayout

  • Hi,

    I have started learning Qt, recently. So, I could have overlooked something here. The crash occurs when I try to repeatedly add QWidget object to subclassed QDialog. There is the code that reproduces the crash:

    #include <QApplication>
    #include <QDialog>
    #include <QGridLayout>
    #include <QLabel>

    class Gui {

    QWidget mWidget;
    Gui(){ mWidget=nullptr; }

    if(mWidget == nullptr){

    // adding layout
    mWidget = new QWidget();
    QGridLayout *gridLayout = new QGridLayout();
    // adding label
    QLabel *label = new QLabel("Label");
    gridLayout->addWidget(label, 0,0);


    return mWidget;


    class GuiContainer : public QDialog{

    Gui *cGui;
    QGridLayout *mGridLayout;

    GuiContainer(Gui *gui){
    cGui = gui;
    mGridLayout = new QGridLayout();
    /A/mGridLayout->addWidget(cGui->getWidget()); // crash here

    // another crash scenario
    ///B/setLayout(mGridLayout); // blocks here

    resize(100, 100);
    delete mGridLayout;


    int main(int argc, char *argv[])
    QApplication a(argc, argv);

    Gui *gui = new Gui();

    GuiContainer *guiContainerA = new GuiContainer(gui);
    delete guiContainerA;

    GuiContainer *guiContainerB = new GuiContainer(gui); // crash here
    delete guiContainerB;

    return a.exec();


    I would appreciate your thoughts on this.

    Additional information:
    OS: Windows 7; Qt: 5.2.1; compiler: msvc2012, 64bits.

  • Lifetime Qt Champion

    Hi and welcome to devnet,

    When deleting guiContainerA, you delete also all children thus mWidget from Gui, so with guiContainerB you try to access an invalid pointer.

    It's a pretty strange design, what are you trying to achieve ?

  • Thank you for your replay. This solved the issue:
    cGui->getWidget()->setParent(nullptr); // parent removal
    delete mGridLayout;

    Design... well, let me show you a bigger picture. There is what I am trying to achieve "summary":https://www.dropbox.com/s/ath03c34zyz4mza/2014-08-04_summary.docx . Currently, I have decided to use QDockWidget instead of QDialog. p.s. sorry for my English.

Log in to reply