Mikhail
Mikhail

Reputation: 8028

Align text in a QComboBox without making it editable?

I have a QComboBox that looks like: enter image description here

Online you see a lot of people posting code to center the label on QComboBox that looks like:

 auto cmb = new QComboBox(parent);
 cmb->setEditable(true);
 cmb->lineEdit()->setReadOnly(true);
 cmb->lineEdit()->setAlignment(Qt::AlignCenter);

This doesn't work because it changes the behavior of the widget, requiring the user to use tiny navigation buttons at the side of the widget: enter image description here

I tried to use a style sheet property but it seems to have no effect

{
             cmb->setProperty("text-align", "center");
             cmb->style()->unpolish(cmb);
             cmb->style()->polish(cmb);
             cmb->update();
}

Anybody know how to center a QComboBox without setting it to editable mode? C++/Python solutions are fine.

Upvotes: 6

Views: 10644

Answers (2)

eiilpux20
eiilpux20

Reputation: 21

Override the paintEvent, copy the qt source code, except:

painter.drawControl(QStyle::CE_ComboBoxLabel, opt);

This is to prevent drawing text.

And draw the text:

QPainter painter2(this);
QStyleOptionButton buttonOpt;
buttonOpt.initFrom(this);  // init states, such as hover, disable

QRect editRect = this->style()->subControlRect(QStyle::CC_ComboBox, &opt, QStyle::SC_ComboBoxEditField, this);
buttonOpt.rect = editRect;  // text rect
buttonOpt.text = opt.currentText;
this->style()->drawControl(QStyle::CE_PushButtonLabel, &buttonOpt, &painter2, this);  // as button text

Now, you can align text in qss:

QComboBox{
    text-align: center;
}

Upvotes: 2

Gene Z. Ragan
Gene Z. Ragan

Reputation: 2863

I looked at the source code of QComboBox and it is drawn using the complex control mechanism defined by each style. Unfortunately (as of Qt 5.12) the alignment of the text label is hard-coded to left-alignment as seen in the following code:

proxy()->drawItemText(p, editRect.adjusted(1, 0, -1, 0), 
                      visualAlignment(cb->direction, Qt::AlignLeft | Qt::AlignVCenter), 
                      cb->palette, cb->state & State_Enabled, cb->currentText);

The only way that I have been able to get the appearance of centered text is by adjusting the padding-left value of the style sheet as so:

comboBox->setStyleSheet("QComboBox {"
                        "   padding-left: 20px;"
                        "}"
                        );

By doing this and by setting the minimum width of the ComboBox so all items are also centered when the drop down is visible, I am able to achievea centered look. You may have to adjust the padding-left amount to get the appearance you want.

Upvotes: 3

Related Questions