How to set the background image of the form in Qt

There are roughly two ways to correctly set the background image of a form in Qt, which will be explained one by one below:

1. Use styleSheet to set the background image of the form

When using the stylesheet to set the background image of the form, you can directly follow the operation as shown in the figure below, as shown in the figure below:

However, it is important to note that:

1. This method does not work in QWidget. If you are careful enough, you will find that using the same method of setting the background image, the background image has not actually changed, but the background image of its sub-window will. changed.

In fact, we can solve this problem by adding a QWidget, that is, add a Frame window in QtDesigner, we only need to set the string value of styleSheet for the newly added Frame window, and all the newly added sub-controls are added to this new Frame window.

2. Friends who have done Qt development should know that Qt's child form will inherit the properties of the parent form, which proves why the background of the parent form will also exist in the child form. This is for this A very reasonable explanation for why. So the question is, how can we make the child form not inherit the background of the parent form?

Now that the reason has been analyzed above, then we know how to solve it. Still open the styleSheet code editing interface, we only need to enter the following lines of code to solve this problem. The specific code is as follows:

#窗体名称 { 
border-image: url(:/HouseRentSystem/Resources/test.png); 
} 
#窗体名称 * { 
border-image:url(); 
}

2. Realized by pure code:

  QWidget *widget = new QWidget();
  widget->setAutoFillBackground(true);
  QPalette palette;
  QPixmap pixmap(":/HouseRentSystem/Resources/test.png");
  palette.setBrush(QPalette::Window, QBrush(pixmap));
  widget->setPalette(palette);
  widget->show();

If you are familiar with styleSheet, I personally recommend that you edit directly in QtDesigner, which will save you a lot of work, at least it will reduce unnecessary redundant code in the program.

The benefits of this article, free to receive Qt development learning materials package, technical video, including (C++ language foundation, C++ design pattern, introduction to Qt programming, QT signal and slot mechanism, QT interface development-image drawing, QT network, QT database programming, QT project actual combat, QSS, OpenCV, Quick module, interview questions, etc.) ↓↓↓↓↓↓See below↓↓Click on the bottom of the article to receive the fee↓↓

Guess you like

Origin blog.csdn.net/m0_60259116/article/details/130623337