QT sets the background image of the non-main window and the background image of the main window (detailed version)

Tip: After the article is written, the table of contents can be automatically generated. For how to generate it, please refer to the help document on the right.


Preface

Most of the online settings for setting window background images are for the main window MainWindow. There are few blogs about setting other non-main window background images. This article mainly sets the main window and non-main window background images from the styleSheet attribute.

1. Set the background image of the main window

(1) First, you need to create a resource file in the project to store the background image. The specific steps are: right-click the project->Add New Project->Qt Resource File.

(2) Find the stylesheet in the property settings of the main window, select Add Resource->background_image, and select the corresponding background image. The path to the image will appear.

Image path example: {background-image: url(:/new/prefix1/C:/Users/dell/Pictures/background4.jpg);

The problem that will arise at this time is: adding a background image will also add a background color to the component, which is not the result we want.

The solution is: you need to add #objectName in front of the image path (the objectName here is the class name of the .ui interface file, which can be viewed through QObject in the properties), and use a pair of curly braces to enclose the image path. Example of modified image path:

#MainWindow {background-image: url(:/new/prefix1/C:/Users/dell/Pictures/background4.jpg)};

2. Set background image for non-main window

(1) The background image setting of the non-main window is similar to that of the main window. The same thing is that it needs to be added through a resource file. The difference is that the non-main window needs to add a component: Widget (select Add in the component box on the left). Then set the background image in styleSheet in the Widget's properties. The setting steps are the same as the main window above. Note that it is set in the styleSheet of the Widget, not in the styleSheet of the .ui interface. This is the only difference from the main window setting.

Another thing to note is that adding a Widget needs to be added before adding various components, that is, the Widget must be added first, otherwise the Widget's background image will cover all components.


Summarize

I hope that my work can provide effective help to you. You are welcome to discuss questions in the comment area.

Guess you like

Origin blog.csdn.net/qwpo135790/article/details/126118740