我想在表单布局中扩展组合框字段,但我似乎找不到正确的咒语组合来实现此目的。关于实际布局管理的具体文档似乎有点薄弱 - 我没有从 doc.qt.io 站点获得很多信息。
这张图片显示了我想要实现的目标:
标签和组合框包含在 QFormLayout 中,而 QFormLayout 又包含在 QVBoxLayout 中。
实际发生的情况是标签/组合占据左侧,组合未扩展到 QVBoxLayout 宽度的大小。
这是我的代码:
import sys
from PyQt6.QtWidgets import QApplication, QComboBox, QDialog, QWidget, QVBoxLayout, QFormLayout, QTableView, QDialogButtonBox, QHeaderView, QLabel, QSizePolicy
from PyQt6.QtCore import Qt
class Dialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setObjectName("Dialog")
self.resize(500, 300)
self.verticalLayoutWidget = QWidget(self)
self.verticalLayoutWidget.resize(495, 295)
self.verticalLayout = QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout.setContentsMargins(5, 5, 5, 5)
self.tableView = QTableView(parent=self.verticalLayoutWidget)
self.tableView.resizeColumnsToContents()
self.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode(1))
self.tableView.SelectionMode(1)
self.verticalLayout.addWidget(self.tableView)
self.myCombo = QComboBox()
self.items = ['N/A', 'Amphibian','Bird','Fish','Invertebrate','Mammal', 'Reptile']
self.myCombo.addItems(self.items)
#self.myCombo.currentTextChanged.connect(self.model.customSlot)
self.myCombo.setSizePolicy(QSizePolicy.horizontalStretch())
self.formLayout = QFormLayout()
self.formLayout.setObjectName("formLayout")
self.formLayout.setContentsMargins(5, 5, 5, 5)
self.label = QLabel('Category', parent=self.verticalLayoutWidget)
self.label.setObjectName("categoriesLabel")
self.formLayout.setWidget(0, QFormLayout.ItemRole.LabelRole, self.label)
self.formLayout.setWidget(0, QFormLayout.ItemRole.FieldRole, self.myCombo)
self.formLayout.setFormAlignment(Qt.AlignmentFlag.AlignLeft) # the documentation specifies Qt.AlignLeft
self.formLayout.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.ExpandingFieldsGrow)
self.verticalLayout.addLayout(self.formLayout)
#self.myCombo.setModelColumn(1)
self.buttonBox = QDialogButtonBox(parent=self.verticalLayoutWidget)
self.buttonBox.setStandardButtons(QDialogButtonBox.StandardButton.Cancel|QDialogButtonBox.StandardButton.Ok)
self.buttonBox.setObjectName("buttonBox")
self.verticalLayout.addWidget(self.buttonBox)
self.buttonBox.rejected.connect(self.close)
#self.buttonBox.accepted.connect(self.model.showModel)
if __name__ == '__main__':
app = QApplication(sys.argv)
ui = Dialog()
ui.show()
app.exec()
我希望我使用的以下几行可能会有所帮助:
self.myCombo.setSizePolicy(QSizePolicy.horizontalStretch())
self.formLayout.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.ExpandingFieldsGrow)
有人对我如何实现这一目标有任何想法吗
我在组合框和表单布局上尝试了数十种 setSizePolicy 组合,但总是生成错误
更改线路:
self.formLayout.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.ExpandingFieldsGrow)
至:
self.formLayout.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
虽然我目前还不知道什么是非固定字段