Align to the right text from QLabel and QLineEdit

mimo picture mimo · Apr 25, 2016 · Viewed 9.4k times · Source

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

Here is how this is rendered:

enter image description here

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

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.

Answer

dtech picture dtech · Apr 28, 2016

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.

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

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:

enter image description here