1

Usually, QLabel is painted with a transparent background. However, if the HTML content is set as a label text, it starts using the parent (I guess) background:

Screenshot

MainWindow:

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{    
    GradientWidget *widget = new GradientWidget(this);
    setCentralWidget(widget);
    resize(400, 300);

    QVBoxLayout *layout = new QVBoxLayout(widget);
    layout->addWidget(new QLabel("Label with a proper (transparent) background", this));
    layout->addWidget(new QLabel("<b>HTML</b> label with an <i>improper</i> (inherited from parent) background"));
}

GradientWidget:

class GradientWidget : public QWidget
{
    Q_OBJECT

public:
    GradientWidget(QWidget *parent = 0) : QWidget(parent) {}

protected:
    void GradientWidget::paintEvent(QPaintEvent *event)
    {
        QLinearGradient gradient(event->rect().topLeft(), event->rect().bottomRight());
        gradient.setColorAt(0, Qt::white);
        gradient.setColorAt(1, Qt::darkYellow);
        QPainter painter(this);
        painter.fillRect(event->rect(), gradient);
    }
};

I'm using Qt 5.2.1 and Windows 10.

Is there any way to get around this strange behavior? Is it a bug or a feature?

John Doe
  • 555
  • 6
  • 17
  • 2
    Could reproduce with Qt 5.9.0 Win10. Seems like a bug to me. I noticed that the label background flickers during resizing / moving, from transparent to improper gradient. Also, when moving the window to my second screen, the background becomes transparent... Report a bug on Qt project – king_nak Apr 05 '18 at 07:56
  • in Linux with Qt 5.10.1 that problem is also reproduced – eyllanesc Apr 05 '18 at 08:26

1 Answers1

1

I'm not sure if it is bug - already reported here QTBUG-67541 or what...

Adding debug line on start of paintEvent method:

qDebug() << "size:" << event->rect() << " w:" << width() << " h:" << height();

then the output show that GradientWidget process paintEvent twice:

size: QRect(0,0 442x305) w: 442 h: 305
size: QRect(12,157 418x136) w: 442 h: 305
size: QRect(0,0 444x305) w: 444 h: 305
size: QRect(12,157 420x136) w: 444 h: 305

(I guess, deprecated value 12 is the 'margin' property of VBoxLayout?)

And this 'rect()' is used for gradient calculation.

Temporary workaround could be:

QLinearGradient gradient({0.0, 0.0}, {static_cast<qreal>(width()), static_cast<qreal>(height())});
Ľubomír Carik
  • 387
  • 5
  • 11