【问题标题】:How to remove spacing inside a gridLayout (QT)?如何删除gridLayout(QT)内的间距?
【发布时间】:2017-02-08 09:31:54
【问题描述】:

我想创建一个包含 2 个小部件的子容器布局。这 2 个小部件应该彼此相邻放置,但我当前的设置之间仍然有一些间距。

我已经将间距设置为 0 setSpacing(0)setContentsMargins(0,0,0,0) 也没有帮助。

我正在使用 PyQt5,但转换 c++ 代码应该不会有问题。

正如你在图片中看到的,仍然有一个小的差距:

(左:LineEdit - 右:PushButton)

import PyQt5.QtCore as qc
import PyQt5.QtGui as qg
import PyQt5.QtWidgets as qw

import sys

class Window(qw.QWidget):
    def __init__(self):
        qw.QWidget.__init__(self)

        self.initUI()

    def initUI(self):
        gridLayout = qw.QGridLayout()

        height = 20

        self.label1 = qw.QLabel("Input:")
        self.label1.setFixedHeight(height)
        gridLayout.addWidget(self.label1, 0, 0)

        # Child Container
        childGridLayout = qw.QGridLayout()
        childGridLayout.setContentsMargins(0,0,0,0)
        childGridLayout.setHorizontalSpacing(0)

        self.lineEdit1 = qw.QLineEdit()
        self.lineEdit1.setFixedSize(25, height)
        childGridLayout.addWidget(self.lineEdit1, 0, 0)

        self.pushButton1 = qw.QPushButton("T")
        self.pushButton1.setFixedSize(20, height)
        childGridLayout.addWidget(self.pushButton1, 0, 1)
        # -----------------
        gridLayout.addItem(childGridLayout, 0,1)

        self.setLayout(gridLayout)


if __name__ == '__main__':

    app = qw.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

【问题讨论】:

  • 您应该发布您的代码并提供一个可验证的最小示例:stackoverflow.com/help/mcve
  • 好的,谢谢,我已经添加了示例代码。

标签: python c++ qt pyqt qgridlayout


【解决方案1】:

QT 文档说: 默认情况下,QLayout 使用样式提供的值。在大多数平台上,所有方向的边距都是 11 像素。

参考:http://doc.qt.io/qt-4.8/qlayout.html#setContentsMargins

因此您可能需要对水平空间使用“setHorizo​​ntalSpacing(int spacing)”,对垂直空间使用“setVerticalSpacing(int spacing)”。

根据文档,这可能会删除您的案例中的空间。 参考:http://doc.qt.io/qt-4.8/qgridlayout.html#horizontalSpacing-prop

如果没有解决,有一个选项可以覆盖空间的样式设置(从布局获取)....我认为这很乏味

如果您想在 QStyle 子类中提供自定义布局间距,请在您的子类中实现一个名为 layoutSpacingImplementation() 的插槽。

更多细节: http://doc.qt.io/qt-4.8/qstyle.html#layoutSpacingImplementation

【讨论】: