重写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>