本文介绍了QComboBox 隐藏了所选项目上的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有一个 QComboBox.

如果 currentText() 对于小部件来说太长,那么我想显示一个省略号.

If the currentText() is too long for the widget then I want to show an ellipsis.

像这样:

所以:

void MyComboBox::paintEvent(QPaintEvent * )
{
      QStylePainter painter(this);
      QStyleOptionComboBox opt;
      initStyleOption(&opt);
      painter.drawComplexControl(QStyle::CC_ComboBox, opt);

      QRect rect = this->rect();
      //this is not ideal
      rect.setLeft(rect.left() + 7);
      rect.setRight(rect.width() - 15);
      //

      QTextOption option;
      option.setAlignment(Qt::AlignVCenter);

      QFontMetrics fontMetric(painter.font());
      const QString elidedText = QAbstractItemDelegate::elidedText(fontMetric, rect.width(), Qt::ElideRight, this->currentText());
      painter.drawText( rect, elidedText, option);
}

这是完美的工作.问题是注释之间的代码,因为我对左右边框的距离进行了硬编码.它让我畏缩.

This is working flawlessy.The problem is the code in between the comments, because I am hardcoding the distances from the left and right border. It makes me cringe.

没有该代码的结果是:

有没有人知道一种更通用的方法来做到这一点,而不需要硬编码?谢谢

Does anybody know a more general way to do this, without hardcoding?Thank you

推荐答案

文本的绘制位置取决于所使用的样式.您可以使用 QStyle::subControlRect 获取有关(某些)子元素定位的信息.与组合框文本最匹配的子控件似乎是 QStyle::SC_ComboBoxEditField,但如果项目有图标,也需要考虑到这一点.如果项目没有图标,您可以使用

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);

您可能想看看如何例如QFusionStyle::drawControl 适用于细节.

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

一般来说,如果您希望所有组合框都省略文本,您应该考虑实现自己的 QProxyStyle 并且只为 QStyle::CE_ComboBoxLabel 覆盖 MyStyle::drawControl.

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.

这篇关于QComboBox 隐藏了所选项目上的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 19:44