Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
78 views
in Technique[技术] by (71.8m points)

python - Setting background color and background image

I wonder how do I set background color AND background image in Python GUI app using PyQt5. 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":

"shadow"

Do you know how to fix these problems?

question from:https://stackoverflow.com/questions/65877269/setting-background-color-and-background-image

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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; 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. 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;
    }''')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...