Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt - Set display text of non-editable QComboBox

Tags:

c++

qt

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.

like image 959
PrisonMonkeys Avatar asked Apr 18 '13 10:04

PrisonMonkeys


2 Answers

I had the same problem when I subclassed QComboBox to make a combo box of check boxes. I wrote a small function to programmatically change the text displayed in the combo box, but I didn't want to enable the user to edit that text. The solution was to set the combo box as editable:

 this->setEditable(true);

and the QComboBox::lineEdit() to read only. Refer to the function:

void CheckedComboBox::setText(QString text)
{
   QLineEdit *displayedText = this->lineEdit();
   displayedText->setText(text);
   displayedText->setReadOnly(true);
}
like image 181
Jays Avatar answered Sep 28 '22 02:09

Jays


Reimplement paintEvent : https://github.com/qt/qtbase/blob/28d1d19a526148845107b631612520a3524b402b/src/widgets/widgets/qcombobox.cpp#L2995

and add this line : opt.currentText = QString(tr("My Custom Text"));

Example :

QCustomCheckComboBoxFilter.h

...
protected:
    void paintEvent(QPaintEvent *e) Q_DECL_OVERRIDE;
...

QCustomCheckComboBoxFilter.cpp

...
void QCustomCheckComboBoxFilter::paintEvent(QPaintEvent *)
{
    QStylePainter painter(this);
    painter.setPen(palette().color(QPalette::Text));

    // draw the combobox frame, focusrect and selected etc.
    QStyleOptionComboBox opt;
    initStyleOption(&opt);
    opt.currentText = QString(tr("My Custom Text"));
    painter.drawComplexControl(QStyle::CC_ComboBox, opt);

    // draw the icon and text
    painter.drawControl(QStyle::CE_ComboBoxLabel, opt);
}
...
like image 24
Sebastien247 Avatar answered Sep 28 '22 02:09

Sebastien247