QLabel is painting improper background when using HTML content

416 Views Asked by At

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?

1

There are 1 best solutions below

0
Ľubomír Carik On BEST ANSWER

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())});