The following code will crash, I found it was related to “new []”
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QPushButton *buttons = new QPushButton[5];
for(int i=0;i<5;++i){
buttons[i].setGeometry(0,0,30,40);
buttons[i].setParent(this);
}
}
after change new[] to normal array, it works fine
#mainwindow.h
QPushButton buttons[5];
#mainwindow.cpp
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
for(int i=0;i<5;++i){
buttons[i].setGeometry(0,0,30,40);
buttons[i].setParent(this);
}
}
any ideas? thanks
I’m no Qt expert, but as far as I can tell, a
QObjectassumes ownership of all its child objects (itdeletes them in the destructor).If that is the case, you’re not supposed to do any of those things you’re doing – every
QPushButtonshould be allocated dynamically and individually usingnew, and the fact that your second example doesn’t crash is what’s weird.