CCC
CCC

Reputation: 2242

How to make QWidget background with specified png file?

MyDialog::MyDialog(QWidget* parent, Qt::WindowFlags f)
    : QWidget(parent, Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint)    
    , _pixmap(new QPixmap(myPngFile))
{
    QPalette palette;
    palette.setBrush(this->backgroundRole(), QBrush(*_pixmap));
    this->setPalette(palette);

    setFixedSize(_pixmap->size());
 }

myPngFile define the png path. The problem is the transparent part in png file showed black when I show MyDialog, how do I correct it to load myPngFile?

I am using Windows platform with Qt4.8

Please do not use stylesheet.

Upvotes: 0

Views: 2599

Answers (3)

tomvodi
tomvodi

Reputation: 5897

If you really don't want to use style sheets, your problem could be solved by overwriting the paint event of your MyDialog class like in the answer of this stackoverflow question: Background image not showing on QWidget

But I would also recommend using style sheets for your problem.

Upvotes: 0

pnezis
pnezis

Reputation: 12331

I cannot understand why you do not want to use stylesheets since this it the preferred way. Use the setStylesheet method of QWidget

setStyleSheet("background-image: url(:/images/pixmap.png);");

Where pixmap.png will be located in the resource file under the images prefix. For more details check the Qt stylesheet examples.

Upvotes: 0

trompa
trompa

Reputation: 2017

Use

setAttribute(Qt::WA_TranslucentBackground);

Take a look at this:

specifically:

QPixmap aPixmap(":/splash.png");
QLabel* aWidget = new QLabel(0, Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint);
aWidget->setAttribute(Qt::WA_TranslucentBackground);
aWidget->setPixmap(aPixmap);
aWidget->show();

And docs:

Creating Translucent Windows Since Qt 4.5, it has been possible to create windows with translucent regions on window systems that support compositing. To enable this feature in a top-level widget, set its Qt::WA_TranslucentBackground attribute with setAttribute() and ensure that its background is painted with non-opaque colors in the regions you want to be partially transparent.

Platform notes: X11: This feature relies on the use of an X server that supports ARGB visuals and a compositing window manager. Windows: The widget needs to have the Qt::FramelessWindowHint window flag set for the translucency to work.

(This bold part you already do, but for future comers better to make it visible)

Upvotes: 1

Related Questions