PDA

View Full Version : QComboBox crash



sfilez
7th July 2009, 22:50
Hi!

When I try to call QComboBox::addItem from another function in my class than the constructor, my application crashes.
I've made a short application to reproduce the crash, here's the code (.zip included for those who want).

ComboBoxCrash.pro


HEADERS += GUI.h
SOURCES += GUI.cpp \
main.cpp


main.cpp


#include <QtCore/QCoreApplication>
#include <QtGui>
#include "GUI.h"


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

ComboBoxCrash *MainWindow = new ComboBoxCrash;
MainWindow->show();
return a.exec();
}


GUI.h


#ifndef GUI_H
#define GUI_H

#include <QWidget>

class QComboBox;
class QPushButton;

class ComboBoxCrash : public QWidget{
Q_OBJECT

public:
ComboBoxCrash(QWidget *parent=0);
public slots:
void function();
private:
QComboBox *comboBox;
QPushButton *crashButton;
};

#endif // GUI_H


GUI.cpp


#include <QtGui>
#include "GUI.h"

ComboBoxCrash::ComboBoxCrash(QWidget *parent) : QWidget(parent){

QComboBox *comboBox = new QComboBox;
QPushButton *crashButton = new QPushButton("Crash");

QGridLayout *mainLayout = new QGridLayout;
mainLayout->addWidget(comboBox,0,0);
mainLayout->addWidget(crashButton,0,1);
setLayout(mainLayout);
setWindowTitle("ComboBox Crash");

comboBox->addItem("Item1");
comboBox->addItem("Item2");
comboBox->addItem("Item3");

connect(crashButton, SIGNAL(clicked()), this, SLOT(function()));
}

void ComboBoxCrash::function(){
comboBox->addItem("Item4");
}


When the function which calls addItem is called, the application crashes.
I'm using Qt 4.5.2 and Qt Creator 1.2.0 under Windows XP SP2.

If anyone know why this happens, or even better, have a solution, I would be very happy.

Thanks in advance :)

wysota
7th July 2009, 23:06
Oh, that's easy. You have two "comboBox" variables - one is a member variable and the other is a local variable created (and destroyed) in the constructor. You are assigning an object to the local one and try to dereference the member which obviously results in a crash.

sfilez
7th July 2009, 23:16
Thanks for the fast reply wysota! :)

What a silly mistake, got it fixed now. :o

sunil.thaha
7th July 2009, 23:17
Replace



QComboBox *comboBox = new QComboBox;
QPushButton *crashButton = new QPushButton("Crash");
replace that with


comboBox = new QComboBox;
crashButton = new QPushButton("Crash");
:-)

sfilez
7th July 2009, 23:31
Already fixed it, but thanks for replying anyways sunil.thaha :)