从QLabel和QLineEdit中右对齐文本

6

我有一个QLabel,它的大小和对齐方式与下面的一个QLineEdit相同:

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的文本完全右对齐?

如果您找到适用于所有平台的解决方案,并且在lineEditlabel的字体大小不同时也有效,则会获得完整奖励。


正如您所看到的,QLineEdit 在文本和边框之间使用了一个分隔空间(很像QLayout的边距)。您可以在 label周围添加布局来模拟这种行为。 - Zaiborg
2
请查看以下内容: http://doc.qt.io/qt-4.8/qlabel.html#indent-prop - Ankur
1
如果您需要计算精确的填充值,可以查看 QLineEdit::textMargins() 并考虑边框宽度。 - ymoreau
3个回答

9
很遗憾,至少不能直接实现,右边距不起作用,即使文本明显向左偏移,右边距始终为0。原因是该偏移量并非由边距确定,而是取决于平台GUI样式和特定字体度量的组合,其值在类公共接口中“方便地”不可用,因此无法获取。
您可以轻松获取字体度量,但无法获取QStyleOptionFrame,因为所需方法受保护,访问它需要子类化QLineEdit。但是,如果您很幸运,该值很可能为零,因此您可以使用以下简单方法:
  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进行子类化,仔细检查其绘制事件,确定偏移量是在哪里被计算的,并将该值存储在公共成员中,以便从外部访问并用于偏移标签。我个人运气很好,使用了这段代码:

enter image description here


这是相当简单的代码!但由于在QTextEdit字体大小大于QLabel时它无法工作,所以我没有回答这个问题。 - mimo

4

你是否可以使用两个QLineEdits代替使用一个QLineEdit和一个QLabel呢?

请考虑以下内容:

QWidget* widget = new QWidget();
// Original line edit
QLineEdit *lineEdit1 = new QLineEdit("999");
lineEdit1->setFixedWidth(100);
lineEdit1->setAlignment(Qt::AlignRight);
lineEdit1->setStyleSheet("border-width: 2px;");
// A suggestion if you want a label
QLabel *label = new QLabel("999");
label->setFixedWidth(100);
label->setAlignment(Qt::AlignRight);
label->setStyleSheet("border: 2px solid rgba(255, 0, 0, 0%)");
// Alternatively if you can use another QLineEdit
QLineEdit *lineEdit2 = new QLineEdit("999");
lineEdit2->setFixedWidth(100);
lineEdit2->setAlignment(Qt::AlignRight);
lineEdit2->setReadOnly(true);
lineEdit2->setStyleSheet("background: rgba(0, 0, 0, 0%);  "
                         "border-width: 2px;              "
                         "border-style: solid;            "
                         "border-color: rgba(0, 0, 0, 0%);");
// Bring it all together
QLayout *layout = new QVBoxLayout(widget);
layout->addWidget(lineEdit1);
layout->addWidget(label);
layout->addWidget(lineEdit2);
widget->show();

它会强制所有边框为2像素,因此在不同的平台上应该都是相同的。第二个QLineEdit不应该与QLabel看起来不同(文本颜色比标签略暗,这可能是一个好事情,因为它匹配了原始编辑)。使用QLineEdit而不是QLabel的附加好处是现在可以选择值......免责声明:我只在Linux上进行过测试,我没有进行像素级比较。编辑:我发现对于不同的字体大小,对齐失败了。

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接