简体   繁体   English

设置背景颜色和背景图像

[英]Setting background color and background image

I wonder how do I set background color AND background image in Python GUI app using PyQt5.我想知道如何使用 PyQt5 在 Python GUI 应用程序中设置背景颜色和背景图像。 I can't figure out how to set them simultaneously.我不知道如何同时设置它们。 I tried doing我试着做

self.window.setStyleSheet("* {color: qlineargradient(spread:pad, x1:0 y1:0, x2:1 y2:0, stop:0 rgba(0, 0, 0, 255), stop:1 rgba(255, 255, 255, 255));"
                  "background: qlineargradient( x1:0 y1:0, x2:1 y2:0, stop:0 #ffc982, stop:1 #ff9982);}; background-image: url(image.png); background-repeat: no-repeat")

but it is not working.但它不工作。 I'm getting “could not parse stylesheet” error.我收到“无法解析样式表”错误。 Obviously, image is in the same direction as code.显然,图像与代码的方向相同。
Also, when I set only only background image it displays "shadow":此外,当我只设置背景图像时,它会显示“阴影”:

“阴影”

Do you know how to fix these problems?你知道如何解决这些问题吗?

There are two problems:有两个问题:

  1. there is a typo in the second line, as you added a ;} at the end of the background, which makes the stylesheet invalid;第二行有一个错字,因为您在背景末尾添加了一个;} ,这使得样式表无效;
  2. using the " * " universal selector (which is almost the same as using QWidget ) means that all widgets will use the properties declared for it, and since you're probably setting the stylesheet on a QMainWindow (which inherits from QWidget), the image background is shown for both the main window and its central widget;使用“ * ”通用选择器(与使用QWidget几乎相同)意味着所有小部件都将使用为其声明的属性,并且由于您可能在 QMainWindow(继承自 QWidget)上设置样式表,因此图像主 window及其中央小部件均显示背景; the universal selector should be used with care, and especially avoided for top level widgets;应谨慎使用通用选择器,尤其是避免用于顶级小部件;

So, besides fixing the typo, you should apply the background only for the widget you're interested into.因此,除了修正错字之外,您应该只为您感兴趣的小部件应用背景。 A good solution could be to set the object name of the central widget (if it's not already set, for instance when using a Designer file) and use the appropriate selector in the stylesheet.一个好的解决方案可能是设置中央小部件的object 名称(如果尚未设置,例如在使用 Designer 文件时)并在样式表中使用适当的选择器。 I also recommend you to use better format and indentation on stylesheets, as it will makes them more readable, allowing you to find syntax errors more easily.我还建议您在样式表上使用更好的格式和缩进,因为这会使它们更具可读性,让您更容易找到语法错误。

self.window.centralWidget().setObjectName('centralWidget')
self.window.setStyleSheet('''
    QWidget#centralWidget {
        color: qlineargradient(spread:pad, x1:0 y1:0, x2:1 y2:0, 
               stop:0 rgba(0, 0, 0, 255), stop:1 rgba(255, 255, 255, 255));
        background: qlineargradient(x1:0 y1:0, x2:1 y2:0, 
                    stop:0 #ffc982, stop:1 #ff9982);
        background-image: url(image.png);
        background-repeat: no-repeat;
    }''')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM