Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create smooth rounded corners on a popup widget in Qt

I've been searching for hours now - without much luck.

I have a widget with the windowsflag Qt::Popup set, and I'm trying to create smooth rounded corners.

I've tried using a stylesheet, but then the transparent part of the corners become black. The same happens if a overwrite the widget's paint event and draw a rectangle with rounded corners in the widget. I've also tried to set a mask, but the result gets very pixelated.

After some reading I found out that the black corners appears because the widget is a top-level widget. But I would think that it's still possible somehow?

Does anyone know what I can do to either get rid of the black corners or to smoothen the mask? Any ideas are appreciated!

The paint event:

void PopUp::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);

    QColor greyColor(0xFFC5C6C6);
    QRect rect(0, 0, width(), height());  
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setBrush(QBrush(greyColor));
    painter.setPen(QPen(greyColor));
    painter.drawRoundedRect(rect, 10, 10);
}

The function that sets the mask:

void PopUp::setRoundedCorners(int radius)
{
    QRegion verticalRegion(0, radius, width(), height() - 2 * radius);
    QRegion horizontalRegion(radius, 0, width() - 2 * radius, height());
    QRegion circle(0, 0, 2 * radius, 2 * radius, QRegion::Ellipse);

    QRegion region = verticalRegion.united(horizontalRegion);
    region = region.united(circle);
    region = region.united(circle.translated(width() - 2 * radius, 0));
    region = region.united(circle.translated(width() - 2 * radius, height() - 2 * radius));
    region = region.united(circle.translated(0, height() - 2 * radius));

    setMask(region);
}
like image 621
KMK Avatar asked Dec 11 '22 04:12

KMK


1 Answers

  1. Create a widget with Qt::Window | Qt::FramelessWindowHint and Qt::WA_TranslucentBackground flag
  2. Create a QFrame inside of a widget
  3. Set a stylesheel to QFrame, for example:

    border: 1px solid red;

    border-radius: 20px;

    background-color: black;

like image 187
Dmitry Sazonov Avatar answered Dec 28 '22 07:12

Dmitry Sazonov