如何用c++和QT写一个闪闪得爱心?
时间: 2023-05-24 21:03:09 浏览: 221
首先建议在QT中创建一个QWidget窗口,然后使用C语言绘制爱心。
以下是一个简单的C程序,用于绘制一个闪闪得爱心:
```
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define SIZE 100
#define PI 3.14159265358979323846
int main()
{
int i, j, n;
double x, y;
char heart[SIZE][SIZE] = {' '};
printf("Enter the size of the heart:");
scanf("%d", &n);
for (i = 0; i <= 2 * n; i++)
{
for (j = 0; j <= 2 * n; j++)
{
x = (double)(j - n) / n;
y = (double)(n - i) / n;
if (pow(x, 2) + pow(y, 2) <= 1)
{
if (pow(x - 0.5, 2) + pow(y, 2) <= 0.25 || pow(x + 0.5, 2) + pow(y, 2) <= 0.25)
{
heart[i][j] = '*';
}
}
}
}
for (i = 0; i <= 2 * n; i++)
{
for (j = 0; j <= 2 * n; j++)
{
printf("%c", heart[i][j]);
}
printf("\n");
}
return 0;
}
```
然后,我们可以在QT应用程序中使用QPainter类,在一个QWidget上绘制出这个爱心。
以下是应用程序的C++代码:
```
#include <QtWidgets/QApplication>
#include <QtWidgets/QWidget>
#include <QtGui/QPainter>
class HeartWidget : public QWidget
{
Q_OBJECT
public:
HeartWidget(QWidget *parent = nullptr);
protected:
void paintEvent(QPaintEvent *event);
private:
int size = 100;
};
HeartWidget::HeartWidget(QWidget *parent) : QWidget(parent)
{
}
void HeartWidget::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
QSize widgetSize = this->size();
int xCenter = widgetSize.width() / 2;
int yCenter = widgetSize.height() / 2;
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setRenderHint(QPainter::HighQualityAntialiasing, true);
painter.setBrush(Qt::red);
QPolygonF heartPolygon;
for (int i = 0; i <= 2 * size; i++)
{
for (int j = 0; j <= 2 * size; j++)
{
double x = (double)(j - size) / size;
double y = (double)(size - i) / size;
if (pow(x, 2) + pow(y, 2) <= 1)
{
if (pow(x - 0.5, 2) + pow(y, 2) <= 0.25 || pow(x + 0.5, 2) + pow(y, 2) <= 0.25)
{
QPointF point(xCenter + x * size, yCenter + y * size);
heartPolygon.append(point);
}
}
}
}
painter.drawPolygon(heartPolygon);
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
HeartWidget widget;
widget.resize(500, 500);
widget.show();
return a.exec();
}
```
阅读全文