Layout crashes (when the program ends, but after all code in the program has executed???)



  • All,
    I have a small Qt program that crashes apparently after the last of my code executes??? I've pared the code down to only 3 small files:

    main.cpp

    @
    #include <QApplication>
    #include "mainwindow.h"

    int main(int argc, char *argv[])
    {
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
    }
    @

    mainwindow.h

    @
    #ifndef MAINWINDOW_H
    #define MAINWINDOW_H
    #include <QMainWindow>
    #include <QWidget>
    #include <QLabel>
    #include <QVBoxLayout>
    class MainWindow : public QMainWindow
    {
    Q_OBJECT
    public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow();
    QLabel m_oSpectrogram_ch1;
    QWidget m_CentralWidget;
    QVBoxLayout *m_pMainLayout;
    };
    #endif // MAINWINDOW_H
    @

    mainwindow.cpp

    @
    #include <QMainWindow>
    #include <QVBoxLayout>
    #include "mainwindow.h"
    MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    {

    m_pMainLayout = new QVBoxLayout;
    m_pMainLayout->addWidget(&m_oSpectrogram_ch1);
    
    m_CentralWidget.setLayout(m_pMainLayout);
    setCentralWidget(&m_CentralWidget);
    

    }

    MainWindow::~MainWindow()
    {
    delete m_pMainLayout;
    return;
    }
    @

    Any suggestions?

    [edit: added missing coding tags @ SGaist]


  • Lifetime Qt Champion

    Hi,

    Don't delete m_pMainLayout, it's set on m_CentralWidget and will be deleted when it's destroyed.



  • SGaist,
    Dude you REALLY are a mad scientist! I only posted a couple of minutes ago...

    I did try not deleting the m_pMainLayout. The program still crashes on exit. So apparently the program can even be one line smaller and still crash... I can break in the destructor of MainWindow, and see that it did execute, and in main I can break on the return statement. The program seems to crash when return a.exec() executes.


  • Lifetime Qt Champion

    You should also allocate m_CentralWidget and m_oSpectrogram_ch1 on the heap rather than the stack



  • SGaist has it RIGHT!

    #include <QMainWindow>
    #include <QFormLayout>
    #include "mainwindow.h"
    MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    {

    m_pMainLayout = new QVBoxLayout;
    m_pMainLayout->addWidget(&m_oSpectrogram_ch1);
    
    m_pCentralWidget = new QWidget;
    m_pCentralWidget->setLayout(m_pMainLayout);
    setCentralWidget(m_pCentralWidget);
    

    }

    MainWindow::~MainWindow()
    {

    }

    The above code does NOT crash on exit...

    Thanks!



  • [[blank-post-content-placeholder]]


  • Lifetime Qt Champion

    You should also allocate m_oSpectrogram_ch1 on the heap


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.