如何在 QHBoxLayout 中对齐两个小部件,其中一个最左对齐,一个最右对齐?

How to align two widgets in a QHBoxLayout where one is aligned far left, and one is aligned far right?

我想要一个 QHBoxLayout,其中一个 QLabel 在最左边,一个 QLabel 在最右边。

我的 Google-fu 让我失望了。 :( 我找不到解决方案。

这是带有两个 QLabel 小部件的 QHBoxLayout 的屏幕截图:

无论我怎么尝试,我都无法让第二个 QLabel 小部件在最右边对齐。

粗略地说,我试过这样的事情:

QHBoxLayout* const hboxLayout = new QHBoxLayout{};
hboxLayout->addWidget(m_leftLabel, 1);
hboxLayout->addStretch(1);
hboxLayout->addWidget(m_rightLabel, 0, Qt::AlignmentFlag::AlignRight);

我为第一个 addWidget() 调用和 addStretch().

尝试了各种较大的拉伸值

我也试过:

m_rightLabel->setAlignment(Qt::AlignmentFlag::AlignRight)

None 这些解决方案有效。我确信解决方案非常简单 (!),但我找不到它。

我该怎么做?

我的解决办法是在中间设置一个拉伸:

#include <QtWidgets>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QWidget w;
    QHBoxLayout *lay = new QHBoxLayout(&w);
    lay->addWidget(new QLabel("Left"));
    lay->addStretch();
    lay->addWidget(new QLabel("Right"));
    w.show();
    return a.exec();
}