Qt:关于自定义widget显示不出背景颜色的问题

重写paintEvent

添加头文件:

#include <QPaintEvent>
#include <QStyleOption>
#include <QPainter>

在.h文件中:public下

void paintEvent(QPaintEvent *e);

在.cpp文件中

void RightWidget::paintEvent(QPaintEvent *e){
    QStyleOption opt;
    opt.init(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}

再对该自定义widget的样式表进行设置:

this->setStyleSheet("background: papayawhip;");


或者直接在重写paintEvent时,利用笔刷等添加颜色

void RightWidget::paintEvent(QPaintEvent *e){
    QStyleOption opt;
    opt.init(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);

 
 
    QPainterPath path;
    path.addRect(0, 0, 600, 500);
    p.setRenderHint(QPainter::Antialiasing);
    p.fillPath(path, QBrush(Qt::yellow));
    p.setPen(Qt::NoPen);
    p.setBrush(Qt::yellow);
    p.drawRect(rect());
}

此时需添加头文件

#include <QPainterPath>


猜你喜欢

转载自blog.csdn.net/qq_37430374/article/details/78336953