Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QDialog with transparent background color

Tags:

qt

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?

like image 472
Pieter Avatar asked Dec 20 '22 22:12

Pieter


1 Answers

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();
}
like image 76
Anthony Avatar answered Jan 11 '23 20:01

Anthony