2

I have the following QFormLayout with a short-value row and a long-value row

layout = QFormLayout()
layout.setLabelAlignment(Qt.AlignLeft)
layout.setFormAlignment(Qt.AlignLeft)

layout.addRow(QLabel('Label short'), QLabel('2'))
layout.addRow(QLabel('Label long'), QLabel('1234567890'))

What I get is:

Label short    2
Label long     1234567890

What I would like is:

Label short             2
Label long     1234567890

I will call the first column the label column and the second column the value column.

  • Using setFormAlignment(), I can move the entire form to the left or to the right, but the value column alignment stays the same
  • Using setLabelAlignment(), I can change the label column, but not the value column
  • Using setAlignment() does not seem to have any effect

Is there an endpoint for controlling the alignment on the second column?

Andrei Cioara
  • 3,404
  • 5
  • 34
  • 62
  • change to `QLabel('2', alignment=Qt.AlignRight)`, You must apply the alignment to the QLabel, not the QFormLayout – eyllanesc Apr 07 '19 at 22:30

2 Answers2

2

Try it:

from PyQt5.QtCore    import *
from PyQt5.QtGui     import *
from PyQt5.QtWidgets import *


class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)

        centralWidget = QWidget()
        self.setCentralWidget(centralWidget)

        layout = QFormLayout(centralWidget)
        layout.setLabelAlignment(Qt.AlignLeft)
        layout.setFormAlignment(Qt.AlignLeft)

        layout.addRow(QLabel('Label short'), QLabel('2',          alignment=Qt.AlignRight))
        layout.addRow(QLabel('Label long'),  QLabel('1234567890', alignment=Qt.AlignRight))

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

enter image description here

S. Nick
  • 12,879
  • 8
  • 25
  • 33
  • Alright, so there must be something wrong with my code, since I have exactly that (but with other widgets around) and it does not work. The labels in fact shrink to text (I verified by adding `QLabel{background: red}` to the stylesheet. I will decompose my app, see if I can trace the issue. Thank you for your answer. – Andrei Cioara Apr 08 '19 at 11:51
0

Using a QLabel you should be able to set the horizontal text alignment to the right using AlignRight

Something like (using C++, but you have the same options in Python)

label->setAlignment(Qt::AlignBottom | Qt::AlignRight);

Gianluca
  • 3,227
  • 2
  • 34
  • 35