源码依然学习自刘典武大神(csdn名字:feiyangqingyun)
(1)如果只有一个widget时,设置过小的size,会出现如下错误信息
setGeometry: Unable to set geometry 100x200+910+404 on QWidgetWindow/'barrulerWindow'. Resulting geometry: 180x200+910+404 (frame: 11, 45, 11, 11, custom margin: 0, 0, 0, 0, minimum size: 0x0, maximum size: 16777215x16777215).
因为红色部分已经是最小了,所有设置布局失败。
(2) 绘制的过程
背景:
painter.save();
QLinearGradient bgGradient(QPointF(0,0),QPointF(0,height()));
bgGradient.setColorAt(0.0,QColor(100, 100, 100));
bgGradient.setColorAt(1.0,QColor(60, 60, 60));
painter.setBrush(bgGradient);
painter.drawRect(rect());
painter.restore();
这里可以学习一下如何使用QLinearGradient(线性渐变),我们让效果跟明显一些:
QLinearGradient bgGradient(QPointF(0,0),QPointF(0,height()));
bgGradient.setColorAt(0.0,QColor(0,0,0));
bgGradient.setColorAt(0.5,QColor(255,0,0));
bgGradient.setColorAt(1.0,QColor(255,255,255));
painter.setBrush(bgGradient);
painter.drawRect(rect());
从(0,0)到(0,height()):颜色从黑色变为红色,再变为白色
竖线,横线:
painter.save();
painter.translate(40,20);//偏移
QPen pen;
pen.setColor(QColor(255,255,255));
pen.setWidth(1);
painter.setPen(pen);
painter.drawLine(QPoint(0,0),QPoint(0,height()-40));
for(int i=100;i>=0;i--)
{
int len;
if(i%10==0){
//长线
len=10;
}
else{
len=5;
}
qreal Y=1.0*(100-i)*(height()-40)/100;
painter.drawLine(QPointF(0,Y),QPointF(len,Y));
}
painter.restore();
数字:
painter.save();
painter.translate(40,20);
QPen pen;
pen.setColor(QColor(255,255,255));
pen.setWidth(2);
painter.setPen(pen);
for(int i=100;i>=0;i=i-10)
{
qreal Y=1.0*(100-i)*(height()-40)/100;
QRectF rect(-60,Y-20,55,40);
painter.drawText(rect,Qt::AlignRight|Qt::AlignVCenter,QString::number(i));
}
painter.restore();
背景柱体:
painter.save();
painter.translate(40+10+3,20);
painter.setPen(Qt::NoPen);
painter.setBrush(QBrush(QColor(220, 220, 220)));
painter.drawRect(0,0,width()-(40+10+3)-20,height()-40);
painter.restore();
颜色柱体:
painter.save();
painter.translate(40+10+3,height()-20);
painter.setPen(Qt::NoPen);
//颜色:
//100, 184, 255
//255, 107, 107
//24, 189, 155
//0, 255, 255
painter.setBrush(QBrush(bar_color));
one_part=1.0*(height()-40)/100;
painter.drawRect(0,-one_part*part_num,width()-(40+10+3)-20,one_part*part_num);
painter.restore();
小想法:
其实就是一些简单图形的组合,搭配好的颜色渐变,创造出好看的图形。
把源码贴出来,属实有点水字数的感觉了,但就当是记录了。