创建QSector类(使用Qt和QPaint)



我创建了一个类名QSector来绘制一个扇区,如下所示:http://www.philadelphia-reflections.com/images/GDP_Composition_By_Sector_Graph.jpg

QValue是一个具有两个属性Label(String)和Value(double)的类QSector类由4个属性组成,继承自QWidget

  • Q油漆工(画东西)
  • QRect(大小和位置)
  • QVector(存储扇区、值和标签的所有数据)
  • 双倍总和(计算QValue值的总和(稍后计算百分比))

这是代码::

// <c++>
class QValue
{
public:
    QValue(QString a = "", double b = 0): f_label(a), f_value(b) {}
    double value()  {   return f_value; }
    QString label() {   return f_label; }
    void setValue(double a)  {  f_value = a;    }
    void setLabel(QString a) {  f_label = a;    }
    void set(QString a, double b)   {   f_label = a;    f_value = b;    }
private:
    QString f_label;
    double  f_value;
};
class QSector : public QWidget
{
    Q_OBJECT
public:
    QSector(int width, int height, QWidget *parent = 0)
    : QWidget(parent), f_total(0)
    {
        f_rect = new QRect(1, 1, width - 3 , height - 3);
        this->resize(width, height);
        f_paint = new QPainter;
    }
    void paintEvent(QPaintEvent* event = 0)
    {
        QBrush brush;
        brush.setColor(QColor(25, 25, 255));
        brush.setStyle(Qt::SolidPattern);
        int startAngle  = 0;
        int spanAngle   = 0;
        f_paint->begin(this);
        for (int i = 0; i < f_data.size(); i++)
        {
            int c = ( i * 150) % 255;
            brush.setColor(QColor(c, 25, 255));
            f_paint->setBrush(brush);
    // 5760 = 360 * 16 = 100%;  total = 100% => Value * 5760 / total = span angle
            spanAngle = (5760 * f_data[i].value()) / f_total;
            f_paint->drawPie(*f_rect, startAngle, spanAngle);
            startAngle = spanAngle;
        }
        f_paint->end();
    }
    void add(QString Label, double Value)
    {
        f_data.push_back(QValue(Label, Value));
        f_total = f_total + Value;
        update();   //   => paintEvent();
    }
    void add(QValue a)
    {
        f_data.push_back(a);
        f_total = f_total + a.value();
        update();   //   => paintEvent();
    }
signals:
public slots:
private:
    QPainter *f_paint;
    QRect    *f_rect;
    QVector<QValue>  f_data;
    double  f_total;
};

一切编译。

问题来了当我做::

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    int w = 300;
    int h = 300;
    QSector test(w, h);
    for (int i = 0, n  = 10; i < n; i++)
        test.add("", 10);
    test.show();
    return app.exec();
}

程序只绘制前2个部分并停止(扇区应该有10个相等的部分,它只有2个)

我不明白它为什么停止画画。如果我把扇区切成两半,效果很好,但从3开始,它只画出2部分

问题总结:https://i.stack.imgur.com/5jyi6.png(图像1,扇区划分为1)(图像2,扇区划分为2)(图3,扇区划分为3)(图4,扇区分成10)

我怀疑

startAngle = spanAngle;

应该是

startAngle += spanAngle;

看起来你只是在以相同的角度一遍又一遍地重新绘制同一个馅饼片。

最新更新