Set Vertical Alignment of QFormLayout QLabel

南笙酒味 提交于 2019-12-06 06:22:46

I don't think there is an elegant solution to your problem. From QFormLayout's source code:

void QFormLayoutPrivate::arrangeWidgets(const QVector<QLayoutStruct>& layouts, QRect &rect)
{
    // [...]
    if (label) {
        int height = layouts.at(label->vLayoutIndex).size;
        if ((label->expandingDirections() & Qt::Vertical) == 0) {
            /*
                If the field on the right-hand side is tall,
                we want the label to be top-aligned, but not too
                much. So we introduce a 7 / 4 factor so that it
                gets some extra pixels at the top.
            */
            height = qMin(height,
                      qMin(label->sizeHint.height() * 7 / 4,
                           label->maxSize.height()));
            }

   [1]  QSize sz(qMin(label->layoutWidth, label->sizeHint.width()), height);
        int x = leftOffset + rect.x() + label->layoutPos;
   [2]  if (fixedAlignment(q->labelAlignment(), layoutDirection) & Qt::AlignRight)
   [ ]      x += label->layoutWidth - sz.width();
   [ ]  QPoint p(x, layouts.at(label->vLayoutIndex).pos);
        // ### expansion & sizepolicy stuff

        label->setGeometry(QStyle::visualRect(layoutDirection, rect, QRect(p, sz)));
    }
    // [...]
}

What do we see here?

  • [1] Labels do not stretch horizontally
  • [2] Labels can only be aligned left (by default) or right

So you have to either somehow manually synchronize labels' widths (e.g. set fixed one) or abandon QFormLayout and use QGridLayout instead.

"[2] Labels can only be aligned left (by default) or right" - I don't believe this is true.

Your code doesn't run for me, so I can't test your exact code. However, this method works for other widgets: notice the use of | to separate the various positional commands.

label2.setAlignment(PyQt5.QtCore.Qt.AlignLeft|PyQt5.QtCore.Qt.AlignVCenter)

I get this is a few years old, so you've probably come up with another way, but this method works well for me.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!