How can I initialize a default value of QComboBox without to click it?

13,860

Solution 1

I solved the problem. The ui->combBox->setCurrentIndex(1); was in constructor before connect(ui->combBox,SIGNAL(currentIndexChanged(int)).... @Nikos C. thank you very much for a good tip.

Solution 2

Are you sure there's at least two values in the QComboBox? Counting begins from 0, not 1. If you want to select the first value, you need to:

ui->combBox->setCurrentIndex(0);

If that's not the problem, and you indeed have two values in the combo box, then make sure that the ui has been set up first. This call needs to execute first:

ui->setupUi(this);

It's what actually fills the combo box with the values specified in the .ui file.

Share:
13,860

Related videos on Youtube

Viktor Tarasov
Author by

Viktor Tarasov

Updated on September 17, 2022

Comments

  • Viktor Tarasov
    Viktor Tarasov over 1 year

    How can I initialize a default value of QComboBox without to click it? I tried with

    ui->combBox->setCurrentIndex(1);
    

    but when I read the value at first I get unfortunately a -1 and only after the QComboBox was clicked its value become 1.

    • tmpearce
      tmpearce over 11 years
      Does the combobox have at least 2 items when you try to set the index to 1?
  • Viktor Tarasov
    Viktor Tarasov over 11 years
    Yes, I'm sure. The values: true(1) and false(0) were defined in MainWindow.ui file. And then in constructor I try to set value ui->combBox->setCurrentIndex(1);
  • Viktor Tarasov
    Viktor Tarasov over 11 years
    I can set the value in the MainWindow to true(1) or false(0) it works correct, but if read the value of the QComboBox before to click it, I get a -1 :((
  • Nikos C.
    Nikos C. over 11 years
    Are you trying to select index 1 before the ui has been setup, perhaps? That is, before the ui->setupUi(this); call in the constructor?
  • Viktor Tarasov
    Viktor Tarasov over 11 years
    But I've just looked it. It's not the problem: at first I call ui->setupUi(this); and then ui->combBox->setCurrentIndex(0); :(( It's so fare correct.
  • Nikos C.
    Nikos C. over 11 years
    Make sure you don't call ui->setupUi(this) again later. Qt writes that call automatically when you create the .ui and .cpp files. You could also post the code of the constructor in your question, so that we can verify this.
  • Viktor Tarasov
    Viktor Tarasov over 11 years
    @Nikos Chantziaras "Make sure you don't call ui->setupUi(this) again later." I'm sure. That's not problem.. also my question stay up to date :((
  • Nikos C.
    Nikos C. over 11 years
    Still, you might want to post the constructor in your question. Maybe then someone can spot what's wrong.