1

通常,QLabel涂有透明背景。但是,如果 HTML 内容被设置为标签文本,它开始使用父(我猜)背景:

截屏

主窗口:

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

渐变小部件:

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

我正在使用Qt 5.2.1Windows 10

有没有办法解决这种奇怪的行为?它是错误还是功能?

4

1 回答 1

1

我不确定这是否是错误 - 已在此处报告QTBUG-67541或什么...

在 paintEvent 方法的开始处添加调试行:

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

然后输出显示 GradientWidget 处理了两次paintEvent:

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

(我猜,弃用的值 12 是 VBoxLayout 的 'margin' 属性?)

而这个 'rect()' 用于梯度计算。

临时解决方法可能是:

QLinearGradient gradient({0.0, 0.0}, {static_cast<qreal>(width()), static_cast<qreal>(height())});
于 2018-04-11T16:06:22.270 回答