QFormLayout 不扩展左列小部件的宽度

问题描述 投票:0回答:1

我正在尝试在从右到左的应用程序中创建表单布局。我认为扩展字段增长标志不起作用,因为最常见的用法是将输入字段放在右侧。某些输入小部件没有扩展宽度策略,而且看起来很糟糕。我能做什么?

演示代码:

from PySide6.QtWidgets import QApplication, QMainWindow, QWidget, QFormLayout, QLabel, QLineEdit, QSpinBox


class FormLayoutDemo(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)

        self.central_layout = QFormLayout()

        # This does not seem to work :(
        self.central_layout.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.ExpandingFieldsGrow)

        self.central_widget.setLayout(self.central_layout)

        self.name_label = QLabel("Name")
        self.name_input = QLineEdit()
        self.central_layout.addRow(self.name_input, self.name_label)

        self.age_label = QLabel("Age")
        self.age_input = QSpinBox()
        # Also not working
        self.age_input.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.central_layout.addRow(self.age_input, self.age_label)


if __name__ == "__main__":
    app = QApplication()
    main_window = FormLayoutDemo()
    main_window.show()
    app.exec()
python pyside qtwidgets
1个回答
0
投票

QFormLayout 将行中的第一个小部件视为标签,将第二个小部件视为字段,因此假设您交换了它们,

fieldGrowthPolicy
将应用于 QLabel 小部件。此外,具有
LabelRole
的项目的大小策略可能由 QFormLayout 内部管理,因此在小部件上设置它也不会产生影响。

而是将其父小部件的

layoutDirection
设置为
RightToLeft
,然后照常使用表单布局,首先使用标签,然后使用字段。

class FormLayoutDemo(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.central_widget = QWidget()
        
        self.central_widget.setLayoutDirection(Qt.RightToLeft)
        
        self.setCentralWidget(self.central_widget)
        self.central_layout = QFormLayout()
        self.central_widget.setLayout(self.central_layout)

        self.name_label = QLabel("Name")
        self.name_input = QLineEdit()
        self.central_layout.addRow(self.name_label, self.name_input)

        self.age_label = QLabel("Age")
        self.age_input = QSpinBox()
        self.central_layout.addRow(self.age_label, self.age_input)
© www.soinside.com 2019 - 2024. All rights reserved.