Skip to main content
标签ad报错:该广告ID(9)不存在。
  主页 > Qt入门

一个qt/c++ demo,用于显示 Pythagoras Tree(毕达哥拉斯树) 分形图

2023-04-24 浏览:
标签ad报错:该广告ID(7)不存在。

#include <QApplication>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QVector>
#include <QPointF>
#include <QPen>

// 递归生成 Pythagoras Tree 的点集
void generatePythagorasTree(QGraphicsScene &scene, const QPointF &origin, double angle, double length, int depth)
{
    if (depth == 0) {
        return;
    }

    // 计算下一个点的位置和角度
    double x = origin.x() + length * qCos(angle);
    double y = origin.y() + length * qSin(angle);
    double newAngle1 = angle - M_PI / 4.0;
    double newAngle2 = angle + M_PI / 4.0;

    // 添加直线和矩形
    QPen pen;
    pen.setColor(Qt::GlobalColor::red);
    scene.addLine(origin.x(), origin.y(), x, y, pen);
    scene.addRect(x - length / 2.0, y - length / 2.0, length, length, pen);

    // 递归生成子树
    generatePythagorasTree(scene, QPointF(x, y), newAngle1, length / qSqrt(2), depth - 1);
    generatePythagorasTree(scene, QPointF(x, y), newAngle2, length / qSqrt(2), depth - 1);
}

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QGraphicsScene scene;
    QGraphicsView view(&scene);

    generatePythagorasTree(scene, QPointF(300, 600), -M_PI / 2.0, 200.0, 10); // 生成 Pythagoras Tree

    view.show();

    return app.exec();
}