创建类,继承自QWidget
重载函数 paintEvent
void CtrlDraw::paintEvent(QPaintEvent *event)
{
//创建Image
QImage image(this->width(),this->height(),QImage::Format_ARGB32);
QPainter p;
p.begin(&image);
//设置渲染,启动反锯齿
p.setRenderHint(QPainter:: Antialiasing, true);
//背景色
p.fillRect(0, 0,this->width(),this->height(), Qt::black);
//画笔
QPen pen(Qt::white, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
//设置画笔
p.setPen(pen);
//直线
p.drawLine(10,10,100,100);
pen.setColor(Qt::yellow);
pen.setWidth(3);
pen.setStyle( Qt::DashLine);
p.setPen(pen);
//圆或椭圆
p.drawEllipse(10, 10,30, 30);
pen.setStyle( Qt::SolidLine);
p.setPen(pen);
//圆弧(逆势针 1/16th of a degree)
p.drawArc(50,50,80,80,90*16,90*16);
//印字
p.fillRect(50,10,100,20, Qt::gray);
p.drawText(50,10,100,20, Qt::AlignCenter, "测试(居中)");
QFont font("Microsoft YaHei",20);
// 使用字体
p.setFont(font);
//字体参考线
p.drawLine(20,150,100,150);
p.drawLine(20,150,20,100);
QFontMetrics fontMetrics(font);
p.drawText(QPointF(105,150-fontMetrics.height()/2 +fontMetrics.ascent()), "X");
QRect rect = fontMetrics.boundingRect("Y");
p.drawText(QPointF(20-rect.width()/2,100-fontMetrics.height()+fontMetrics.ascent()), "Y");
p.end();
//界面显示Image
QPainter painter(this);
painter.drawImage(QRectF(0, 0,this->width(), this->height()), image);
}
界面中添加控件 QWidget,并提升为自己定义的类,
如需刷新,调用 控件 repaint();