【问题标题】:Layout in QWidget makes background white when adding a stretchQWidget 中的布局在添加拉伸时使背景变为白色
【发布时间】:2019-10-04 16:30:54
【问题描述】:

我正在使用 PyQt5 和它的样式系统来为我的应用程序创建一个现代外观的 GUI,但我似乎无法做到这一点。

所以我的服装标题栏都在工作。它有 3 个部分;一个菜单栏、一个标签和另一个菜单栏,用作关闭、最小化和最大化的标题栏按钮。 我需要此标题栏为浅灰色,但如下图所示,元素之间存在空白。

现在是什么:

应该是什么:

当您运行下面的示例时,您可以看到标签之间有一些空白区域。即使标签在没有样式的框内,样式也是在小部件上设置的。

#### 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 的背景颜色设置为浅灰色并忽略拉伸。

有人知道解决方法吗?

【问题讨论】:

  • @eyllanesc 我已经更新了示例代码,如果您安装了 pyqt5,您现在可以运行它。
  • 我已经执行了您提供的代码:imgur.com/a/4qsEcNU,它与您提供的图像无关,您可以放置​​您使用该代码获得的图像以及您想要获得的图像。
  • @eyllanesc 我已经编辑了你的截图。 imgur.com/a/kC59Vf4
  • @eyllanesc 这与标题栏的想法相同。只有我大大简化了它。我将背景设为蓝色,将 labelbackground 设为红色,以便突出显示差异。标签之间的空白不应存在。

标签: python pyqt pyqt5 qlayout


【解决方案1】:

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

# ...
parentLayout = QHBoxLayout()
parentLayout.setSpacing(0)
# ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-27
    • 1970-01-01
    • 2020-11-10
    • 2014-08-14
    • 1970-01-01
    • 2013-09-20
    • 1970-01-01
    相关资源
    最近更新 更多