[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 {
private:
QWidget mWidget;
public:
Gui(){ mWidget=nullptr; }
QWidget getWidget(){if(mWidget == nullptr){
// adding layout mWidget = new QWidget(); QGridLayout *gridLayout = new QGridLayout(); mWidget->setLayout(gridLayout); // adding label QLabel *label = new QLabel("Label"); gridLayout->addWidget(label, 0,0);
}
return mWidget;
}};
class GuiContainer : public QDialog{
private:
Gui *cGui;
QGridLayout *mGridLayout;public:
GuiContainer(Gui *gui){
cGui = gui;
mGridLayout = new QGridLayout();
/A/setLayout(mGridLayout);
/A/mGridLayout->addWidget(cGui->getWidget()); // crash here// another crash scenario
///B/mGridLayout->addWidget(cGui->getWidget());
///B/setLayout(mGridLayout); // blocks hereresize(100, 100);
}
~GuiContainer(){
if(layout()){
mGridLayout->removeWidget(cGui->getWidget());
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. -
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:
@
if(layout()){
mGridLayout->removeWidget(cGui->getWidget());
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.