class QGraphicsHexagonItem : public QGraphicsPolygonItem{private:protected: void mousePressEvent(QMouseEvent* MouseEvent);public: QGraphicsHexagonItem(QPoint center, int radius);};
#ifndef __QGRAPHICSHEXAGONITEM_H__#define __QGRAPHICSHEXAGONITEM_H__#include <QObject>#include <QGraphicsPolygonItem>#include <QPen>#include <QMouseEvent>class QGraphicsHexagonItem : public QGraphicsPolygonItem{private:protected: void mousePressEvent(QMouseEvent* MouseEvent);public: QGraphicsHexagonItem(QPoint center, int radius);};#endif
#include "QGraphicsHexagonItem.h"QGraphicsHexagonItem::QGraphicsHexagonItem(QPoint center, int radius){ QVector<QPoint> vector; int R = radius; int r = R*sqrt(3.0)/2; QPen pen; pen.setWidthF(2.5); vector.push_back(QPoint(center.x(), center.y()-R)); vector.push_back(QPoint(center.x()+r, center.y()-r/2)); vector.push_back(QPoint(center.x()+r, center.y()+r/2)); vector.push_back(QPoint(center.x(), center.y()+R)); vector.push_back(QPoint(center.x()-r, center.y()+r/2)); vector.push_back(QPoint(center.x()-r, center.y()-r/2)); this->setPolygon(QPolygon(vector)); this->setPen(pen); this->setBrush(QBrush(Qt::green));}void QGraphicsHexagonItem::mousePressEvent(QMouseEvent* MouseEvent){ //...}
QGraphicsScene* scene = new QGraphicsScene(this); int width = 580; int height = 310; int space = 5; scene->setSceneRect(0, 0, width-2, height-2); int R = 15; int r = R*sqrt(3.0)/2; QPoint center(space+r, space+R); QPen pen; pen.setWidthF(2.5); bool t = false; for(int x, y=0;center.y()+R<=height-2-space;center.setY(center.y()+R+r/2),t=!t,++y) { x=0; for(center.setX(space+r+(t?r:0));center.x()+r<=width-2-space;center.setX(center.x()+r+r),++x) scene->addItem(new QGraphicsHexagonItem(center, R)); } QGraphicsView* view = new QGraphicsView(scene, this); view->setGeometry(10, 50, width, height); view->show();