Search code examples
c++qtqcombobox

Qt - Set display text of non-editable QComboBox


I would like to set the text of a QComboBox to some custom text (that is not in the QComboBox's list), without adding this text as an item of the QComboBox. This behaviour is achievable on an editable QComboBox with QComboBox::setEditText(const QString & text). On a non-editable QComboBox, however, this function does nothing.

Is it possible to programmatically set the display/edit text of a non-editable QComboBox to something that is not in its list? Or do I have to find another way (e.g. use a QPushButton with a popup menu)

EDIT: Consider an editable QComboBox with InsertPolicy QComboBox::NoInsert. If the user types in something and hits enter, the entered value will be used but not added to the list. What I want is this behaviour to change the 'current' text programmatically, but without allowing the user to type in some text himself. The user can choose something from the QComboBox, but some time later, I may want to override the 'current' text.


Solution

  • I ended up using a QPushButton with a popup menu. I added the items I had in the list of my QComboBox as QActions to the menu. A menu can be set on a QPushButton with

    QPushButton::setMenu(QMenu* menu)
    

    . The text on the button can easily be set with

    QPushButton::setText(const QString &)
    

    and is unrelated to the text in the popup menu, which is what I wanted.