Using an alpha transparent mask on a QWidget?

2019-02-26 02:40发布

问题:

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:

and a widget like this:

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

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

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:

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.