代码
piechart.h
#include <QWidget>
#include <QPainter>
class PieChartWidget: public QWidget
{
Q_OBJECT
public:
PieChartWidget(QWidget* parent = nullptr): QWidget(parent)
{
setFixedSize(490,300);
setStyleSheet("background: lightblue;");
}
protected:
void paintEvent(QPaintEvent* event) override {
Q_UNUSED(event)
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
QFont font;
font.setPointSize(16);
painter.setFont(font);
painter.drawText(width()/2-100, 10, 200, 30, Qt::AlignCenter, "饼状图标题");
int startAngle = 10;
int totalAngle = 360;
QVector<QColor> colors = {Qt::red, Qt::green, Qt::yellow, Qt::darkBlue};
QRectF deviceRect(30, 40, 180, height() - 120);
QVector<int> deviceAngles = {120, 240};
for (int i = 0; i < deviceAngles.size(); ++i) {
painter.setBrush(colors[i]);
painter.drawPie(deviceRect, startAngle * 16, deviceAngles[i] * 16);
startAngle += deviceAngles[i];
}
int legendX = width() - 420;
int legendY = 235;
font.setPointSize(10);
painter.setFont(font);
painter.setBrush(colors[0]);
painter.drawRect(legendX, legendY, 15, 15);
painter.drawText(legendX + 30, legendY +10, "周一:"+QString::number(deviceAngles[0]));
painter.setBrush(colors[1]);
painter.drawRect(legendX, legendY + 30, 15, 15);
painter.drawText(legendX + 30, legendY + 40, "周二:"+QString::number(deviceAngles[1]));
QRectF cameraRect(250, 40, 180, height() - 120);
QVector<int> cameraAngles = {120, 240};
for (int i = 0; i < cameraAngles.size(); ++i) {
painter.setBrush(colors[i]);
painter.drawPie(cameraRect, startAngle * 16, cameraAngles[i] * 16);
startAngle += cameraAngles[i];
}
legendX = width() - 200;
painter.setBrush(colors[2]);
painter.drawRect(legendX, legendY, 15, 15);
painter.drawText(legendX + 30, legendY +10, "公交车:"+QString::number(cameraAngles[0]));
painter.setBrush(colors[3]);
painter.drawRect(legendX, legendY + 30, 15, 15);
painter.drawText(legendX + 30, legendY + 40, "地铁:"+QString::number(cameraAngles[1]));
}
};
在代码中使用
PieChartWidget* piechart = new PieChartWidget();
piechart->show();
效果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/cc3a9a9a7fe41e4cd3b9c8aa80a0ea26.png#pic_center)
注意: 如果重写了paintEvent的QWidget是在程序运行时就开始执行paintEvent函数,但是这个qwidget却没有在程序运行时作为主页面或主页面的一部分显示出来,而需要通过其他操作(比如点击按钮)才能显示出来,可能会出现部分图形或者文字没有画出来的情况。如图:![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8a06af139ed66f0ee7fe8425eda6c844.png#pic_center)
此图没有画出图例的原因:在上面的 int legendX = width() - 420; 和legendX = width() - 200;这两行代码执行时,没有获取到qwidget的width()。
解决:只要将int legendX = width() - 420; 和legendX = width() - 200;改成具体的位置就行。
int legendX = 70;
legendX = 290;