We are developing an application in QT5.6.2, wherein we are using stylesheet file to set background image for QLabel using "background-image" property in stylesheet. And on a button press, want to draw a transparent section on this QLabel.
We are using QPainter class, setCompositionMode method to get the result.
Below code snippet works, if we apply the image to QLabel in source code. However, if the same image is applied with stylesheet, then this does not work.
// Code snippet - DOES NOT WORK
// CSS
QLabel#backgroundLabel{
image: url("wallpaper/background1_800_600.png");
}
For context, here is how we want to use the background, and how setting it in the code works:
// CPP source
const QPixmap* pixmap = ui->backgroundLabel->pixmap();
if ( pixmap == nullptr)
{
qDebug() << "source pixmap png is null";
return;
}
QImage sourceImage(pixmap->toImage()); // DOES NOT WORK
// QImage sourceImage("wallpaper/background1_800_600.png"); // This works
if(sourceImage.isNull()){
qDebug() << "source Image png is null";
}else{
qDebug() << "source Image png is available";
}
QPainter painter(&sourceImage);
painter.setCompositionMode(QPainter::CompositionMode_Source);
painter.fillRect(100,89,600,380, Qt::transparent);
painter.end();
ui->backgroundLabel->setPixmap(QPixmap::fromImage(sourceImage));
With the non-working code, we are getting output as - source pixmap png is null. i.e. pixmap pointer is NULL.
With working part (sourceImage is directly loaded from file), we get the background image with a rectangular hole in it. - We need this output.