【问题标题】:QLabel is painting improper background when using HTML content使用 HTML 内容时,QLabel 正在绘制不正确的背景
【发布时间】:2018-04-05 07:44:00
【问题描述】:

通常,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

有什么办法可以避免这种奇怪的行为吗?是错误还是功能?

【问题讨论】:

  • 可以用 Qt 5.9.0 Win10 重现。对我来说似乎是一个错误。我注意到标签背景在调整大小/移动过程中闪烁,从透明到不正确的渐变。另外,当将窗口移动到我的第二个屏幕时,背景变得透明......报告Qt项目的错误
  • 在带有 Qt 5.10.1 的 Linux 中也重现了该问题

标签: qt qt5 qpainter qlabel qt5.2


【解决方案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())});

【讨论】:

    猜你喜欢
    • 2011-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-02
    相关资源
    最近更新 更多