我创建了一个类名 QSector 来绘制如下所示的扇区: http ://www.philadelphia-reflections.com/images/GDP_Composition_By_Sector_Graph.jpg
QValue 是一个有 2 个属性 Label (String) 和 Value (double) 的类,QSector 类由 4 个属性组成,继承自 QWidget
- QPainter(画东西)
- 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 个部分
问题总结:http: //i.imgur.com/Mssjisd.png (图 1,扇区分为 1)(图 2,扇区分为 2)(图 3,扇区分为 3)(图 4,扇区分为 10)