QComboBox elided text on selected item

霸气de小男生 提交于 2019-12-04 17:15:32

Where the text should be drawn exactly depends on the used style. You can get information about (some of) the positioning of subelements with QStyle::subControlRect. The subcontrol that matches the combo box text best seems to be QStyle::SC_ComboBoxEditField, though if the item has an icon, this needs to be taken into account as well. If the items do not have icons, you can go with

  QRect textRect = style()->subControlRect(QStyle::CC_ComboBox, &opt, QStyle::SC_ComboBoxEditField, this);
  QFontMetrics fontMetric(painter.font());
  const QString elidedText = QAbstractItemDelegate::elidedText(fontMetric, textRect.width(), Qt::ElideRight, this->currentText());
  opt.currentText = elidedText;
  painter.drawControl(QStyle::CE_ComboBoxLabel, opt);

You might want to have a look at how e.g. QFusionStyle::drawControl works for details.

In general, if you want all your combo boxes to elide the text, you should consider implementing your own QProxyStyle and only override MyStyle::drawControl for QStyle::CE_ComboBoxLabel.

This is the solution I've been using:

void CustomComboBox::paintEvent(QPaintEvent * /*event*/)
{
    QStyleOptionComboBox opt;
    initStyleOption(&opt);

    QStylePainter p(this);
    p.drawComplexControl(QStyle::CC_ComboBox, opt);

    QRect textRect = style()->subControlRect(QStyle::CC_ComboBox, &opt, QStyle::SC_ComboBoxEditField, this);
    opt.currentText = p.fontMetrics().elidedText(opt.currentText, Qt::ElideRight, textRect.width());
    p.drawControl(QStyle::CE_ComboBoxLabel, opt);
}

This approach is very similar to a combination of your sample code and the snippet E4z9 suggested. I just thought I'd include the whole method for others coming here in the future.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!