How to make QWidget background with specified png file?

妖精的绣舞 提交于 2019-12-11 19:19:10

问题


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.


回答1:


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.




回答2:


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)




回答3:


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.



来源:https://stackoverflow.com/questions/17804101/how-to-make-qwidget-background-with-specified-png-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!