Confused about memory management



  • I have done some research and it seems like the safe way is to declare a parent for all the widgets. I know that some of this is done implicitly (for example when you add a layout or widget). However, for my code I did it for everything just to be thorough. Yet, when I run valgrind I still get memory leaks. Anyone know what can cause these memory leaks?

    testGUI::testGUI(char** argv, QWidget* parent) :
    	QWidget(parent), _argv(argv) {
    
    	    // Main window and layout
    	QWidget* mainWindow = new QWidget;
    	QVBoxLayout *mainLayout = new QVBoxLayout(mainWindow);
    
    	// Tab widget
    	QTabWidget* tabWidget = new QTabWidget(mainWindow);
    
    	// The pages in the tab widget
    	QWidget* uInt8Window = new QWidget(mainWindow);
    	uInt8Window->setWindowTitle(QString("Page 1"));
    
    	QTableView* tableView = new QTableView(mainWindow);
    	QStandardItemModel* model = new QStandardItemModel(5, 5, mainWindow);
    	for (int row = 0; row < 5; ++row) {
    		model->setItem(row, 0, new QStandardItem("3"));
    		model->setItem(row, 1, new QStandardItem(5));
    		model->setItem(row, 2, new QStandardItem(2));
    		model->setItem(row, 3, new QStandardItem(1));
    		model->setItem(row, 4, new QStandardItem(5));
    	}
    
    	tableView->setModel(model);
    
    	// Setting the tab page layouts
    	_layout = new QVBoxLayout(mainWindow);
    	_layout->addWidget(tableView);
    
    	uInt8Window->setLayout(_layout);
    
    	// Add the pages to the tab widget
    	tabWidget->addTab(uInt8Window, "Page 1");
    
    	// Add the tab widget to the main layout and show
    	mainLayout->addWidget(tabWidget);
    	mainWindow->setLayout(mainLayout);
    	mainWindow->show();
    
    }

  • Moderators

    Unless I'm mistaken you gave a parent to everything except mainWindow.

    As your testGUI class inherits QWidget I'm guessing you should have done this: QWidget* mainWindow = new QWidget(this); and remove the mainWindow->show(); call (assuming you show testGUI instance somewhere).

    Note though that this way mainWindow will not be part of any layout so resizing and such won't work. Since testGUI is already a widget you don't really need mainWindow here. Just set the layout on your testGUI instance: this->setLayout(mainLayout).


Log in to reply
 

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