多个QHBoxLayout使用权重时组件无法对齐的问题求助
多个QHBoxLayout使用权重时组件无法对齐的问题求助
我在QGIS中用Python 3.12.12创建了一个自定义的QDialog,布局代码如下:
layoutOne = QHBoxLayout() oneA = QRadioButton("Option 1A") oneB = QRadioButton("Option 1B") layoutOne.addWidget(oneA) layoutOne.addWidget(oneB) #layoutOne.addStretch(1) #layoutOne.addSpacing(100) groupOne = QButtonGroup(self) groupOne.addButton(oneA) groupOne.addButton(oneB) groupOne.setExclusive(True) layoutTwo = QHBoxLayout() two = QCheckBox("Checkbox") layoutTwo.addWidget(two) two.setChecked(True) layoutThree = QHBoxLayout() threeA = QRadioButton("Option 3A") threeB = QRadioButton("Option 3B") threeC = QRadioButton("Option 3C") layoutThree.addWidget(threeA) layoutThree.addWidget(threeB) layoutThree.addWidget(threeC) groupThree = QButtonGroup() groupThree.addButton(threeA) groupThree.addButton(threeB) groupThree.addButton(threeC) groupThree.setExclusive(True) self.layout = QVBoxLayout() self.layout.addLayout(layoutOne) self.layout.addLayout(layoutTwo) self.layout.addLayout(layoutThree) self.setLayout(self.layout)
这个布局的显示效果如下:

我想让“Option 1B”和“Option 3B”处于同一列,所以给布局添加了权重/拉伸设置:
layoutOne.addWidget(oneA, 1) layoutOne.addWidget(oneB, 2)
添加后的效果变成了这样:

但你也能看到,它们并没有完美对齐——第二列有2像素左右的偏移。如果我再添加一个包含两个元素的QHBoxLayout,它会和layoutOne完美对齐,但它的第二个元素依然会和layoutThree的对应元素有偏移。
如果用layoutOne.addStretch(1)代替权重设置的话,几乎就没什么间距了(oneB直接贴在oneA右边),这不是我想要的;同时我也不想用layoutOne.addSpacing(100)这种固定像素宽度的设置,因为我希望对话框能根据字体大小(用户的系统设置)自动调整自身的宽高。
想请教大家:这个偏移是怎么造成的?有没有办法让它们正确对齐(注意:我不想使用QGridLayout!)?
备注:内容来源于stack exchange,提问作者Neph
相关产品推荐
相关产品推荐

