#ifndef QPOINTSARRAY_H
#define QPOINTSARRAY_H
#include <QGraphicsItem>
#include <QPainter>
#include <QPointF>
#include <QList>
#include <QColor>
class QPointsArray : public QGraphicsItem {
public:
// 构造函数
QPointsArray(int rows, int columns, qreal spacing, const QColor &color = Qt::black, qreal radius = 5.0)
: m_rows(rows), m_columns(columns), m_spacing(spacing), m_color(color), m_radius(radius) {
updatePoints();
}
// 设置行数
void setRows(int rows) {
if (rows != m_rows) {
m_rows = rows;
updatePoints();
update(); // 触发重绘
}
}
// 设置列数
void setColumns(int columns) {
if (columns != m_columns) {
m_columns = columns;
updatePoints();
update(); // 触发重绘
}
}
// 设置点间距
void setSpacing(qreal spacing) {
if (spacing != m_spacing) {
m_spacing = spacing;
updatePoints();
update(); // 触发重绘
}
}
// 设置点的颜色
void setColor(const QColor &color) {
m_color = color;
update(); // 触发重绘
}
// 设置点的半径
void setRadius(qreal radius) {
m_radius = radius;
update(); // 触发重绘
}
// QGraphicsItem 接口实现
QRectF boundingRect() const override {
if (m_points.isEmpty()) {
return QRectF();
}
// 计算包含所有点的矩形
qreal minX = m_points[0].x(), maxX = m_points[0].x();
qreal minY = m_points[0].y(), maxY = m_points[0].y();
for (const QPointF &point : m_points) {
if (point.x() < minX) minX = point.x();
if (point.x() > maxX) maxX = point.x();
if (point.y() < minY) minY = point.y();
if (point.y() > maxY) maxY = point.y();
}
// 扩展矩形以包含点的半径
return QRectF(minX - m_radius, minY - m_radius, maxX - minX + 2 * m_radius, maxY - minY + 2 * m_radius);
}
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override {
Q_UNUSED(option);
Q_UNUSED(widget);
painter->setBrush(m_color);
painter->setPen(Qt::NoPen);
for (const QPointF &point : m_points) {
painter->drawEllipse(point, m_radius, m_radius);
}
}
private:
// 更新点阵
void updatePoints() {
m_points.clear();
for (int row = 0; row < m_rows; ++row) {
for (int col = 0; col < m_columns; ++col) {
m_points.append(QPointF(col * m_spacing, row * m_spacing));
}
}
}
int m_rows; // 行数
int m_columns; // 列数
qreal m_spacing; // 点间距
QColor m_color; // 点的颜色
qreal m_radius; // 点的半径
QList<QPointF> m_points; // 点阵
};
#endif // QPOINTSARRAY_H
应用:
#include <QApplication>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QColor>
#include "qpointsarray.h"
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QGraphicsScene scene;
// 创建 QPointsArray 对象
QPointsArray *pointsArray = new QPointsArray(15, 15, 10.0, Qt::blue, 3.0);
// 将 QPointsArray 添加到场景
scene.addItem(pointsArray);
QGraphicsView view(&scene);
view.resize(400, 300);
view.show();
return app.exec();
}