The purpose of setCurrentIndex is to change the value, so "without the value being overwritten" makes little sense. Create the combo box, attach its model, and then call setCurrentIndex() (with zero as the argument if you know your placeholder is always the first entry in the model, or use your find if not). Where is the problem?
If you want something displayed on the combo box when nothing from the model is selected, i.e. currentIndex() returns -1, then that is a different request. I imagine you could do something in the paintEvent() function of a subclass for the case when the QStyleOptionComboBox current text is empty or currentIndex() is -1
{
Q_OBJECT
public:
}
protected:
painter.
setPen(palette
().
color(QPalette::Text));
// draw the combobox frame, focusrect and selected etc.
initStyleOption(&opt);
painter.
drawComplexControl(QStyle::CC_ComboBox, opt
);
// draw the icon and text
if (!opt.editable && currentIndex() == -1) // <<< we adjust the text displayed when nothing is selected
opt.currentText = tr("{Select one}");
painter.
drawControl(QStyle::CE_ComboBoxLabel, opt
);
}
};
class ComboBox: public QComboBox
{
Q_OBJECT
public:
explicit ComboBox(QWidget *p = 0): QComboBox(p) {
}
protected:
void paintEvent(QPaintEvent *) {
QStylePainter painter(this);
painter.setPen(palette().color(QPalette::Text));
// draw the combobox frame, focusrect and selected etc.
QStyleOptionComboBox opt;
initStyleOption(&opt);
painter.drawComplexControl(QStyle::CC_ComboBox, opt);
// draw the icon and text
if (!opt.editable && currentIndex() == -1) // <<< we adjust the text displayed when nothing is selected
opt.currentText = tr("{Select one}");
painter.drawControl(QStyle::CE_ComboBoxLabel, opt);
}
};
To copy to clipboard, switch view to plain text mode
The text is displayed but is not returned by currentText(), is not selectable by the user once a valid selection is made, and does not need to appear in your model. You should make the text configurable.
BTW: It is not strange that a combo box without an editor would return a null pointer when you ask for the editor. If you then proceeded to use the pointer blindly you will crash.
Bookmarks