QT set background image example(QLable_setstylesheet, QPixmap)

QT set background image example(QLable_setstylesheet, QPixmap)
I had a problem about applying image.

This is problem :
My app is working on an embedded system. I have migrated the app from Qt 5.6 to Qt 5.9.3 and it became very slow. I have checked the output of the top command and realized that my app is causing a CPU utilization of 100%.
So, I have check my app and I have found a problem in this part of the code:
MainWidget::MainWidget(QWidget *parent)
    : QWidget(parent)
{
...

    QPixmap bg(BACK_IMG_PATH);
    bg.fill(Qt::transparent);
    QPalette p(palette());
    p.setBrush(QPalette::Background, bg);
    setAutoFillBackground(true);
    setPalette(p);
...
}
The problem is, that if I add the code for the background, my app becomes extremely slow. However, if I remove this code, my app is working as expected. This cannot be a solution though, cause I need the background.
This problem did not exist before the migration.
I have tried to solve this by reimplementing the paintEvent and using QPainter like this:
void MainWidget::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.drawImage(QRectF(this->x(), this->y(), this->width(), this->height()), QImage("img/bg_1280_720.png"));
}
This result is slightly faster, but still not satisfactory (the cpu utilization is 50%).


How to solve this problem?

before:
#define BACK_IMG_PATH           "/img/bg_1280_720.png"
    QPixmap bg(BACK_IMG_PATH);
    bg.fill(Qt::transparent);
    QPalette p(palette());
    p.setBrush(QPalette::Background, bg);
    setAutoFillBackground(true);
    setPalette(p);


after:

#define BACK_IMG_PATH           "background-image:url(/img/bg_1280_720.png)"
    QLabel *labelBg = new QLabel(this);
    labelBg->setStyleSheet(BACK_IMG_PATH);
    labelBg->setGeometry(this->geometry());


No comments:

Post a Comment

Apartment Buying Guide 2025: Shocking Red Flags You Should NEVER Ignore!

 🏙️ Apartment Buying Guide 2025: Shocking Red Flags You Should NEVER Ignore! 🚨 Are you thinking about buying an apartment in 2025? 🏢  It’...