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

一个qt/c++ demo,用于显示 Cantor Dust(康托尔尘埃) 分形图

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

#include <QtWidgets>

class CantorDustFractal : public QWidget    
{
public:
    CantorDustFractal(QWidget *parent = 0);

protected:
    void paintEvent(QPaintEvent *);

private:
    void drawFractal(QPainter& painter, int xPos, int yPos, int sideLength);
};

CantorDustFractal::CantorDustFractal(QWidget *parent)
    : QWidget(parent)
{   
    setFixedSize(350, 200);
}

void CantorDustFractal::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.setPen(Qt::black);
    painter.setBrush(QBrush(Qt::white));

    int xPos = 30;
    int yPos = 100;
    int sideLength = 250;

    drawFractal(painter, xPos, yPos, sideLength);
}

void CantorDustFractal::drawFractal(QPainter& painter, int xPos, int yPos, int sideLength)
{
    if (sideLength < 2)
    {
        painter.drawRect(xPos, yPos, sideLength, sideLength);
        return;
    }

    // 计算子正方形的边长和位置
    int subLength = sideLength / 3;
    int subXPos = xPos + subLength;

    // 绘制 7 个子图形,除去中心的那个子正方形
    drawFractal(painter, xPos, yPos, subLength, subLength);
    drawFractal(painter, xPos + subLength * 2, yPos, subLength, subLength);
    drawFractal(painter, xPos, yPos + subLength * 2, subLength, subLength);
    drawFractal(painter, xPos + subLength * 2, yPos + subLength * 2, subLength, subLength);
    drawFractal(painter, subXPos, yPos, subLength, subLength);
    drawFractal(painter, subXPos, yPos + subLength * 2, subLength, subLength);
    drawFractal(painter, xPos + subLength, yPos + subLength, subLength, subLength);
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);    
    CantorDustFractal w;
    w.show();

    return a.exec();
}