PDA

View Full Version : [QCombobox] Display decorated value



mentalmushroom
8th May 2012, 14:19
I have a combobox with several predefined values and a one custom item that allows manually enter the value in the edit field of the combobox. When user enters/edits the value, I'd like to show that value as is. But when editing is finished to display the decorated value (e.g. "123 Kb" instead of "123" entered by a user). What is the best way to achieve this? I've tried to use QStyledItemDelegate overriding displayText method, but this doesn't seem to work, because the item in the drop down list should be still called "custom", only edit field value should be decorated.

Spitfire
15th May 2012, 16:15
Try setting custom line edit for the combo box, something like that:


class MyLineEdit : public QLineEdit
{
public:
MyLineEdit( QWidget* parent = 0 ) : QLineEdit( parent ) {}

void focusInEvent( QFocusEvent* e )
{
this->setText( value );
QLineEdit::focusInEvent( e );
}

void focusOutEvent( QFocusEvent* e )
{
this->value = this->text();
if( !this->value.isEmpty() )
{
this->setText( this->value + " Kb" );
}
QLineEdit::focusOutEvent( e );
}

private:
QString value;
};

combobox->setLineEdit( new MyLineEdit( this ) );
This doesn't take into account text set via setText() but it's just an (working) example.

mentalmushroom
16th May 2012, 06:41
Thanks, I've ended up with similar approach, but I worked with combobox only and didn't set custom line edit or subclass it. I just thought maybe it was possible with data roles or delegates, but it seems like it's not.