I want to make the background of a QDialog
transparent so that I can see through the window. I'm asking because I want to use a semi-transparent background image that creates a "rounded corner window" illusion. Using setOpacity
is not an option for me because I want all widgets to remain at full opacity.
Is there a way to achieve this without resorting to native OS APIs?
Use QWidget::setAttribute(Qt::WA_TranslucentBackground);
. Note that this also requires Qt::FramelessWindowHint
to be set.
This example works for me:
#include <QtGui>
class Dialog : public QDialog
{
public:
Dialog() : QDialog(0, Qt::FramelessWindowHint) // hint is required on Windows
{
QPushButton *button = new QPushButton("Some Button", this);
setAttribute(Qt::WA_TranslucentBackground);
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Dialog d;
d.show();
return a.exec();
}
Regarding rounded corners, QWidget::setMask()
will help you.
EDIT: In response to another question below in the comments, here is a working example that uses an image in a resources file, and that overrides QWidget::paintEvent()
:
#include <QtGui>
class Dialog : public QDialog
{
public:
Dialog() : QDialog(0, Qt::FramelessWindowHint) // hint is required on Windows
{
setFixedSize(500, 500); // size of the background image
QPushButton *button = new QPushButton("Some Button", this);
setAttribute(Qt::WA_TranslucentBackground);
}
protected:
void paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.drawImage(QRectF(0, 0, 500, 500), QImage(":/resources/image.png"));
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Dialog d;
d.show();
return a.exec();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With