重写qwidget的paintEvent事件在qwidget中绘制两个饼状图

代码

piechart.h


#include 
#include 
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();

效果

重写qwidget的paintEvent事件在qwidget中绘制两个饼状图_第1张图片

注意: 如果重写了paintEvent的QWidget是在程序运行时就开始执行paintEvent函数,但是这个qwidget却没有在程序运行时作为主页面或主页面的一部分显示出来,而需要通过其他操作(比如点击按钮)才能显示出来,可能会出现部分图形或者文字没有画出来的情况。如图:重写qwidget的paintEvent事件在qwidget中绘制两个饼状图_第2张图片

此图没有画出图例的原因:在上面的 int legendX = width() - 420; 和legendX = width() - 200;这两行代码执行时,没有获取到qwidget的width()。

解决:只要将int legendX = width() - 420; 和legendX = width() - 200;改成具体的位置就行。

int legendX = 70;
legendX = 290;

你可能感兴趣的:(QT,qt5)