QWidget中的布局在添加拉伸时使背景变白

问题描述 投票:0回答:1

我正在使用PyQt5,它是一种样式系统,可以为我的应用程序创建外观现代的GUI,我似乎无法正确地做到这一点。

所以我有一个Costum标题栏都在起作用。它分为三个部分。一个菜单栏,一个标签和另一个用作标题栏按钮的菜单栏,用于关闭,最小和最大化。我需要此标题栏为浅灰色,但是正如您在下图中所看到的,元素之间有空白。

现在是什么:

enter image description here

应该是什么:

enter image description here

运行下面的示例时,您可以看到标签之间有一些空白。即使标签位于没有样式的盒子内,样式还是在小部件上设置的。

#### PyQt imports....
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (QWidget, QHBoxLayout, QMenuBar, QApplication,
                            QLabel, QVBoxLayout)
#### Python imports....
import sys

#### Class for sampleWindow....
class sampleWindow(QWidget):
    def __init__(self):
        super().__init__()

        #### Some window settings....
        self.setWindowTitle('Sample Program')
        self.setGeometry(400, 300, 1000, 500)

        ######## THE SAME PROBLEM BUT THIS TIME NOT IN A QMENUBAR ########
        #### Creating the widget and it's layout....
        parentLayout = QHBoxLayout()
        parentWidget = QWidget()

        #### Creating the elements....
        sampleLabelLeft = QLabel('left')
        sampleLabelCenter = QLabel('center')
        sampleLabelRight = QLabel('right')

        #### Setting alignment for the elements....
        sampleLabelLeft.setAlignment(Qt.AlignLeft)
        sampleLabelCenter.setAlignment(Qt.AlignCenter)
        sampleLabelRight.setAlignment(Qt.AlignRight)

        #### Adding the elements to the parentLayout....
        parentLayout.addWidget(sampleLabelLeft)
        parentLayout.addWidget(sampleLabelCenter)
        parentLayout.addWidget(sampleLabelRight)

        #### Setting parentLayout as layout for parentWidget....
        parentWidget.setLayout(parentLayout)

        #### Set styling for elements....
        self.setStyleSheet('QWidget{background:blue;} QLabel{background:red;}')

        #### Setting some a box to put parentWidget in so it can be set as the main layout....
        mainBox = QVBoxLayout()
        mainBox.addStretch()
        mainBox.addWidget(parentWidget)
        mainBox.addStretch()
        mainBox.setContentsMargins(200,200,200,200)
        self.setLayout(mainBox)

app = QApplication(sys.argv)
sampleWindow = sampleWindow()
sampleWindow.show()
app.exec()

因此,在此之后,我将QWidget的背景色设置为浅灰色,而忽略了拉伸。

有人知道解决方法吗?

python pyqt pyqt5 qlayout
1个回答
0
投票

默认情况下,布局具有与样式有关的spacing,因此针对您的情况的解决方案是将其设置为0:

spacing
© www.soinside.com 2019 - 2024. All rights reserved.