如何删除gridLayout(QT)中的间距?

时间:2016-09-29 22:07:32

标签: python c++ qt pyqt qgridlayout

我想创建一个包含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_())

1 个答案:

答案 0 :(得分:2)

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()的插槽。

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