How to add background image resources in Qt?

There are two ways to add background image resources in Qt.

  1. Utilize the QMainWindow class: In Qt Designer or in code, set the background of QMainWindow to the desired image resource. This can be achieved with the following code:
QMainWindow *window = new QMainWindow();
window->setStyleSheet("background-image: url(:/path/to/image.png)");
  1. Use the QLabel class: In Qt Designer or code, set the background of a QLabel to the desired image resource. This can be achieved with the following code:
QLabel *label = new QLabel();
QPixmap pixmap(":/path/to/image.png");
label->setPixmap(pixmap);
label->setScaledContents(true);

In the .pro file, you will need to add a declaration for the corresponding resource file, as shown below. The :path/to/image.png refers to the path of the image resource file and can be modified according to your needs.

RESOURCES += resource.qrc

The name of the resource file is resource.qrc and can be modified according to the actual situation.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds