Using an alpha transparent mask on a QWidget?

2019-02-26 02:19发布

Is it possible to assign an alpha-transparent mask to a QWidget? I know how to set a mask using setMask but it seems it only supports black&white masks. Is it possible to make it support a true alpha channel?

i.e. currently I have a PNG like this:

enter image description here

and a widget like this:

enter image description here

If I load my PNG in a QPixmap and set it as a mask, I get this (notice the edges):

enter image description here

However I would like to get this (smooth edges):

enter image description here

Any idea how to do that?

Note: I'm doing some more complex drawing on the widget, which must be restricted to the mask area, so I cannot simply set my PNG as the widget's background image.

1条回答
够拽才男人
2楼-- · 2019-02-26 02:38

I think your best route is in QPainter's composition modes.

For example:

QPixmap PixmapToBeMasked(Size);
PixmapToBeMasked.fill(QColor(255, 255, 255, 120));

QPixmap Mask = DoSomethingToGetAMask();

QPainter Painter(&PixmapToBeMasked);
Painter.setCompositionMode(QPainter::CompositionMode_DestinationIn);
Painter.drawPixmap(0, 0, Mask.width(), Mask.height(), Mask);

That will handle drawing your widget nicely. If you still need to mask mouse events you might need to do some extra work though.

查看更多
登录 后发表回答