【发布时间】:2017-02-16 10:22:52
【问题描述】:
考虑QMainWindow 与QWidget 作为中心小部件的情况。这个小部件有一个QHBoxLayout。我向其中添加了另外两个小部件,每个小部件都有一个QVBoxLayout。
我现在想让QVBoxLayout 中的小部件彼此靠近。尝试为此目的使用.setMargin(0)、.setSpacing(0) 和.setContentsMargins(0,0,0,0)。
但是结果是它们的分离实际上是增加而不是减少 - 如图所示(Gain 是我将边距和间距设置为零的小部件)。
下面附加了重现此问题的代码。 (使用QGridLayout 时也会发生同样的情况。)
这是关于两个不同复杂程度的问题:
(a) 由于这两个小部件之间的唯一区别是其中一个将边距和间距设置为零,因此使用的方法调用之一肯定对布局或小部件做了其他事情-特性。通过设置 .setMargin(0)、.setSpacing(0) 和 setContentsMargins(0,0,0,0) 中的任何一个会更改哪个其他属性?
(b)在本例中,如何使文本标签和组合框之间的间距变小?
from PyQt4 import QtGui
import sys
class LabeledComboBox(QtGui.QWidget):
def __init__(self, text="", items=[], parent=None):
super(LabeledComboBox, self).__init__(parent)
self.parent = parent
self.widgetlayout = QtGui.QVBoxLayout(self)
self.widgetlayout.addWidget(QtGui.QLabel(text))
self.Combo = QtGui.QComboBox()
self.Combo.addItems(items)
self.widgetlayout.addWidget(self.Combo)
self.parent.mylayout.addWidget(self)
def printParams(self):
# print some margin/spacing parameters for testing
m = self.widgetlayout.margin()
s = self.widgetlayout.spacing()
cm = self.widgetlayout.getContentsMargins()
print "margin: {m}, spacing: {s}, ContentsMargin: {cm}".format(m=m, s=s, cm=cm)
class App(QtGui.QMainWindow):
def __init__(self, parent=None):
super(App, self).__init__(parent)
self.mainbox = QtGui.QWidget()
self.mylayout = QtGui.QHBoxLayout()
self.mainbox.setLayout(self.mylayout)
self.setCentralWidget(self.mainbox)
self.GainWidget = LabeledComboBox("Gain", ['low', 'medium', 'high'], self)
self.RevolutionsWidget = LabeledComboBox("Revolutions", ['100', '200', '400'], self)
self.GainWidget.printParams()
# this outputs: margin: 9, spacing: 6, ContentsMargin: (9, 9, 9, 9)
# now I set everything to zero
self.GainWidget.widgetlayout.setMargin(0)
self.GainWidget.widgetlayout.setSpacing(0)
self.GainWidget.widgetlayout.setContentsMargins(0,0,0,0)
# check
self.GainWidget.printParams()
# margin: 0, spacing: 0, ContentsMargin: (0, 0, 0, 0)
if __name__=='__main__':
app = QtGui.QApplication(sys.argv)
thisapp = App()
thisapp.show()
sys.exit(app.exec_())
【问题讨论】: