Arbitel Arbitel - 22 days ago 7
C++ Question

Qt Change ComboBox2 based on ComboBox1

Hi I am fairly new to Qt scene and I'm having trouble updating my comboBox2 based on comboBox1 selection.

Everytime I make a change in comboBox1, my app crashed, saying access violation. It's probably very straightforward but here's my code: In this case, the initial comboBox1 has "Car" and "Food". Whenever I switch to "Food", I want my comboBox2 to populate the item "Egg".

Any idea what went wrong ?

main.h

class main:
{
Q_OBJECT


public:
main() {}

public slots :

private slots:
void onComboBoxIndexChanged();

private:
QComboBox* comboBox2;
void run();
};


main.cpp

void main::run()
{
QWidget *w = new QWidget();

QComboBox *comboBox1 = new QComboBox();
QComboBox *comboBox2 = new QComboBox();

comboBox1->addItem("Car");
comboBox1->addItem("Food");

connect(comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(onComboBoxIndexChanged()));
...
}


void main::onComboBoxIndexChanged()
{
QComboBox* combo = dynamic_cast<QComboBox*>(sender());

if (combo == nullptr)
{
return;
}

comboBox2->addItem("Egg");

}

Answer

You didn't fix your typo correctly. There's three things I see wrong, and I would've thought the third one would prevent this from compiling.

First, main.h says that your class name is "main", but in main.cpp, your class is WIPGui. Clearly one of those files isn't the right one. I'm going to proceed assuming that your actual main.h file defines the WIPGui class, but otherwise looks the same.

Second, as Mike tried to point out, in your run function, you have this:

QComboBox *comboBox2 = new QComboBox();

That's creating a local variable in your "run" method; it is not assigning to your class member variable comboBox2. What you want is:

comboBox2 = new QComboBox();

Third, your connect statement shouldn't compile based on the code we're seeing:

connect(comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(onComboBoxIndexChanged()));

The "comboBox" variable doesn't exist anywhere in this code. If you've actually used "comboBox1" in the connect statement, but this is just another typo in the code you've presented here, then the connect statement is fine. If this is a cut-and-paste as-is, then I don't see how this compiles.

Assuming that you've used "comboBox1" in the connect statement, then the real problem is that you're never assigning to the member variable "comboBox2" and when your slot tries to use it, you get a crash.

Comments