本帖最后由 swico 于 2024-6-21 16:45 编辑
记录一下学习qt的qpainter的过程,进度条倾斜绘制,可以直接使用,但是需要自己传递参数,带有详细注释
[C++] 纯文本查看 复制代码 void Widget::drawProgressByQPainter(QPainter *painter, double progressValue, int blockSize)
{
/// x和宽度成倍数增减
painter->setRenderHints(QPainter::Antialiasing);
QRect rect(10, 150, width()-10*2, height()-150*2);
painter->setViewport(rect); // 设置Viewport,显示区域
painter->setWindow(0, 0, 100, 50); // 设置窗口大小,逻辑坐标
// 绘制边框
QPen pen(Qt::white,1); // 设置画笔
painter->setPen(pen);
QBrush brush(Qt::white,Qt::SolidPattern); // 设置画刷
painter->setBrush(brush);
rect.setRect(0, 0, 100, 50); // 在原本的rect下新增rect,设置逻辑边框大小
painter->drawRect(rect);
/// 自定义块的大小,通过进度计算绘制的块数,最后一块可以绘制一部分
/// 先绘制边框,通过rect绘制竖条,pen的width制造margin
/// 解决旋转问题,以及超出部分剪裁
int blockTotalNum = 100 / blockSize; // 100/4=25块
int fillBlockSize = static_cast<int>(progressValue/100 * blockTotalNum); // 25*0.42=10.5块
// double lastFillBlockSize = progressValue * blockTotalNum - fillBlockSize; // 最后一块 0.5
pen.setColor(Qt::white);
brush.setColor(Qt::blue);
painter->setPen(pen); //通过pen的width制造每个竖条的margin
painter->setBrush(brush);
// for循环绘制每一条
for (int i = 0; i < fillBlockSize; ++i)
{
// 旋转,这里需要根据每一条rect
painter->save();
rect.setRect(2+blockSize*i, 5, blockSize, 40); // 当pen的width为1时,边框会遮住左边一部分,手动右移2px
painter->translate(2+blockSize*i+blockSize/2, 5+40/2);
painter->rotate(10);
painter->translate(-(2+blockSize*i+blockSize/2), -(5+40/2));
painter->drawRect(rect); // 根据rect填充进度
painter->restore();
}
} |