Unsolved Bug with setCurrentText on QComboBox
-
Hi guys,
I would like to report a potential bug with method setCurrentText on QComboBox.
I am running Qt Creator 4.8.0 based on Qt 5.12.0 and using Windows 10.I have the following implementation
mLocationComboBox = new QComboBox(); mLocationComboBox->setEditable(true); mLocationComboBox->setMinimumContentsLength(70); mLocationComboBox->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLength); mLocationComboBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); QStringList recentLocations; recentLocations.append(QDir::homePath()); mLocationComboBox->insertItems(0, recentLocations); mLocationComboBox->setCurrentIndex(0); mLocationComboBox->addItem("Here1"); mLocationComboBox->addItem("Here2"); mLocationComboBox->setCurrentText("Here2"); auto currentText = mLocationComboBox->currentText(); // "Here2" auto currentIndex = mLocationComboBox->currentIndex(); // 0
According to the documentation, currentIndex should be set to index of "Here2" that is 2, while it is set to 0.
Thank you!
-
Humor me for a second and run the event loop before you retrieve the index. Something like this:
mLocationComboBox->setCurrentText("Here2"); QCoreApplication::processEvents(); QString currentText = mLocationComboBox->currentText(); // "Here2" int currentIndex = mLocationComboBox->currentIndex(); // 0
What do you get?
-
@kshegunov 😲 don't encourage processEvents() calls!
mLocationComboBox->setCurrentText("Here2"); QMetaObject::InvokeMethod(this, [=]()->void{ QString currentText = mLocationComboBox->currentText(); // "Here2" int currentIndex = mLocationComboBox->currentIndex(); // 0 }, Qt::QueuedConnection);
;-)
-
guys, thank you for the prompt response!
I did check both suggestions and currentIndex equals to 0. -
@Kolya
well looking through the code example you posted, that behavior is not unexpected,you set the combobox to be editable:
setEditable(true);
and according to the docu
The setter setCurrentText() simply calls setEditText() if the combo box is editable. Otherwise, if there is a matching text in the list, currentIndex is set to the corresponding index.
-
@J-Hilk My bad - misinterpreted the documentation :-) Thank you for pointing out!
-
Hi,
@Kolya said in Bug with setCurrentText on QComboBox:
According to the documentation, currentIndex should be set to index of "Here2" that is 2, while it is set to 0.
On a side note, you should not expect 2 but 1. In C++ the index are zero based.