1

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

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

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

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

(左:LineEdit - 右:按钮)

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_())
4

1 回答 1

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#horizo​​ntalSpacing-prop

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

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

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

于 2016-09-29T22:38:24.600 回答