PyQt - 减少widget中的边距和间距*展开* layout

时间:2016-10-07 12:07:18

标签: layout pyqt

考虑QMainWindowQWidget为中心窗口小部件的情况。此小部件有QHBoxLayout。我添加了另外两个小部件,每个小部件都有一个QVBoxLayout。 我现在想让QVBoxLayout内的小部件彼此靠近。尝试使用.setMargin(0).setSpacing(0).setContentsMargins(0,0,0,0)来实现此目的。

然而结果是它们的分离实际上是增加而不是减少 - 如图所示(其中Gain是我将边距和间距设置为零的小部件)。

enter image description here

下面附有重现此问题的代码。 (使用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_())

2 个答案:

答案 0 :(得分:4)

首先:setMargin是一种过时的方法,已被setContentsMargins取代,因此您可以忽略它。

其次:分离的增加是由将边距设置为零引起的。两个垂直布局采用相同的水平布局,因此它们必须具有相同的高度。但是左侧布局没有边距,因此它有更多的空间可用于拉伸。如果两个垂直布局具有相同的设置,则可以通过调整窗口大小将它们的子窗口小部件紧密地挤在一起。

因此,您需要在两个布局上使用setSpacing来更改间距。

答案 1 :(得分:1)

在最新的PyQt 5.10 setContentsMargins方法中运行良好。 您可以为窗口小部件创建布局,然后应用其边距。

widget.layout.setContentsMargins(0,0,0,0)