如何在Qt的QRadioButton中设置下标,上标和其他特殊字符

最佳答案

您可以尝试覆盖paintEvent()QRadioButton(尽管您必须对其进行子类化),然后使用QPainter绘制文本。这是您可以使用的example。我已经尝试过了,除了大小问题外,它运作得比较好:

c++ - 如何在Qt的QRadioButton上设置下标和上标-LMLPHP

我的单选按钮的替代paintEvent(QPaintEvent* event)是:

QRadioButtonRichtTextSupport.h

void QRadioButtonRichtTextSupport::paintEvent(QPaintEvent* event)
{
  // First draw the original content of the radio button - the circle and the plain text
  QRadioButton::paintEvent(event);

  // Get the rectangle of the paint event
  QRect _rect = event->rect();
  QPainter painter(this);
  painter.setRenderHint(QPainter::Antialiasing, true);

  // Erase the text - I have used a translation of 16 along the X axis
  // from the top left corner of the paint rectangle but there might be
  // some less dirty way of doing this. Basically this is used to leave
  // the circle of the radio button intact while erasing the text part
  painter.eraseRect(_rect.topLeft().x()+16, _rect.topLeft().y(), _rect.width()-16, _rect.height());

  // Translate the painter along the X axis with 16
  painter.translate(QPointF(16, 0));
  // Create a text document which supports rich text formatting
  QTextDocument label;
  label.setHtml(this->text());
  // and finally draw the text over the radio button starting from +16 along the X axis
  label.drawContents(&painter);
  painter.end();
}

Widget.cpp
Widget::Widget(QWidget *parent)
  : QWidget(parent)
{
  setLayout(&this->layout);
  // Create the custom radio button. Notice that I've also added a string argument (not present in the default constructor of QRadioButton)
  // to add the ability to set the text upon initialization. This is completely optional
  QRadioButtonRichtTextSupport* rbrt = new QRadioButtonRichtTextSupport("<b>Rich text</b><sup>abc123</sup>", this);
  this->layout.addWidget(rbrt);
}

这里的问题是,我实际上确实设置了单选按钮的文本(使用setText(...)),并且由于单选按钮不支持RTF格式,因此您会得到一个更宽的单选按钮(上图中的文本后的空白区域)实际上是原始文本所在的位置(在我的示例中为<b>Rich text</b><sup>abc123</sup>)。您将需要更多地研究此方法,以了解如何调整大小,以减少“多余”空间。也可以通过覆盖自定义单选按钮。您可以使用resizeEvent(QResizeEvent* event)来获取正在使用的label.documentLayout()->documentSize()的大小,然后添加额外的空间(在我的情况下,我会沿X轴使用QTextDocument来改变的宽度)。

如果由于某种原因这不是您的选择,则复合小部件似乎是最简单的方法-创建具有水平布局的小部件,首先放置不带文本的+16,然后放置带单选按钮文本的QRadioButton

UTF-8的问题在于它仅支持subset of superscript Latin(和希腊字母)字母(例如,您想写上标的QLabel的那一刻就被拧了)。 UTF-16(Qt也支持)中可能有更完善的内容,因此如果创建自己的q或创建复合窗口小部件对您而言不是最佳选择,则您可能需要调查一下。

关于c++ - 如何在Qt的QRadioButton上设置下标和上标,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42451712/

10-11 15:28