对齐到QLabel和QLineEdit的正确文本 [英] Align to the right text from QLabel and QLineEdit

查看:904
本文介绍了对齐到QLabel和QLineEdit的正确文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在QLineEdit的正下方有一个QLabel,具有相同的大小和对齐属性:

I have a QLabel just below a QLineEdit with the same size and alignment properties:

QLineEdit *lineEdit = new QLineEdit("999");
lineEdit->setFixedWidth(100);
lineEdit->setAlignment(Qt::AlignRight);
//
QLabel *label = new QLabel("999");
label->setFixedWidth(100);
label->setAlignment(Qt::AlignRight);
//
QLayout *layout = new QVBoxLayout;
layout->addWidget(lineEdit);
layout->addWidget(label);

这是它的呈现方式:

如何使底部label的文本与lineEdit的文本完全右对齐?

How can I have the text of the bottom label exactly right-aligned to the text of the lineEdit?

全奖,如果您找到了一种适用于所有平台的解决方案,并且当lineEditlabel中的字体大小不同时也适用.

Full award if you find a solution that works on all platforms, and that also works when the font sizes are different in the lineEdit and label.

推荐答案

不幸的是,不可能,至少不是开箱即用,右边距将不起作用,因为即使文本很明显也始终为0向左偏移.原因是此偏移量不是由边距确定的,而是取决于平台GUI样式和所使用的特定字体的度量标准的组合,并且其值在类公共接口中方便地"不可用,这是无法实现的来实现它.

Unfortunately it may not be possible, at least not out of the box, the right margin will not work, as it is always 0 even when the text is obviously offset to the left. The reason for this is this offset is not determined by the margins, but depends on the combination of platform GUI style and particular font's metrics that's being used, and its value is "conveniently" not available in the class public interface, there is no way to get to it.

您可以轻松获取字体指标,但由于所需方法受到保护,因此无法获取QStyleOptionFrame,要访问它,必须将其归为QLineEdit子类.但是,如果幸运的话,该值很可能为零,因此您可以使用以下简单的方法:

You can get the font metrics easily, but you can't get the QStyleOptionFrame as the method required is protected, accessing it will require to subclass QLineEdit. However, if you are lucky, that value is very likely to be zero, so you could go with something as simple as this:

  QVBoxLayout *layout = new QVBoxLayout;
  QLineEdit *lineEdit = new QLineEdit("999");
  lineEdit->setAlignment(Qt::AlignRight);
  QLabel *label = new QLabel("999");
  label->setAlignment(Qt::AlignRight);

  int offsetValue = lineEdit->fontMetrics().averageCharWidth();
  label->setIndent(offsetValue);

  setLayout(layout);
  layout->addWidget(lineEdit);
  layout->addWidget(label);

如果这对您不正常,您只能选择QLineEdit的子类,仔细检查其绘画事件,确定偏移量的计算位置,并将该值存储在公共成员中,以便它可以从外部访问以用于偏移标签.

If that doesn't work correctly for you, you will have no other choice but to subclass QLineEdit, carefully examine its paint event, determine where the offset is being calculated, and store that value in a public member so it can be accessed from the outside to be used to offset the label.

我个人很幸运使用该代码:

I personally got lucky with that code:

这篇关于对齐到QLabel和QLineEdit的正确文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆