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

2024-04-18 09:53:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用PyQt5和它的样式系统为我的应用程序创建一个现代的图形用户界面,我似乎不能得到这个权利

所以我有一个肋骨标题栏在工作。它由3部分组成;一个菜单栏,一个标签和另一个菜单栏作为标题栏按钮关闭,最小和最大化。 我需要这个标题栏是浅灰色的颜色,但正如你可以看到在下面的图片,有白色的元素之间的空间

现在的情况:

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的背景色设置为一点浅灰色,拉伸被忽略

有人知道解决方法吗


Tags: theselffor样式elementsqtpyqt5标题栏