大家知道Qt中有QGraphicsItem这个类,这是图形元素的基类。如果想实现自己的图形元素,那就要继承这个基类。
1.首先我们继承QGraphicsItem,画自己的圆。
MyItem.h
class MyItem : public QGraphicsItem
{
public:
MyItem(double radius, double Radius);
~MyItem();
QRectF boundingRect() const;
void paint(QPainter *painter,const QStyleOptionGraphicsItem *option,QWidget *widget);
protected:
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);//实现圆的拖拽效果
void mouseDoubleClickEvent (QGraphicsSceneMouseEvent *event);//处理鼠标双击事件
private:
double m_radius;
double m_Radius;
bool m_colorFlag;//true:red, flase:black
};
MyItem.cpp
MyItem::MyItem(double radius, double Radius)
{
m_colorFlag = true;
m_radius = radius;
m_Radius = Radius;
setFlags(ItemIsSelectable | ItemIsMovable);
}
MyItem::~MyItem()
{
}
QRectF MyItem::boundingRect() const
{
return QRectF(-m_radius, -m_radius,
2*m_radius, 2*m_radius);
}
void MyItem::paint(QPainter *painter,const QStyleOptionGraphicsItem *option,QWidget *widget)
{
if(m_colorFlag)
painter->setBrush(Qt::blue);
else
painter->setBrush(Qt::red);
painter->drawEllipse(QPointF(0, 0), m_radius, m_radius);
}
void MyItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
qreal x = pos().x();
qreal y = pos().y();
double D = m_Radius - m_radius - 2;
// limit circle position
if(x*x + y*y >D*D)
{
double tmpX = x*D/sqrt(x*x + y*y);
double tmpY = y*D/sqrt(x*x + y*y);
setPos(tmpX, tmpY);
}
QGraphicsItem::mouseReleaseEvent(event);
}
void MyItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{
m_colorFlag = !m_colorFlag;
QGraphicsItem::mouseDoubleClickEvent(event);
update();
}
2.创建一个画布,在画布上添加圆,最后用一个View来管理画布。
MainWindow.cpp
#define RADIUS 100
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
//m_scene = new QGraphicsScene();
//m_scene = new QGraphicsScene(-50, -50, 100, 100);
m_scene = new QGraphicsScene(-100, -100, 200, 200);
m_scene->addEllipse(-100, -100, 200, 200);
m_steelNum = ui->spinBox->value();
MyItem* item = new MyItem(25, RADIUS);
item->setPos(0, 0);
m_scene->addItem(item);
QGraphicsView *view = new QGraphicsView(m_scene);
view->show();
ui->verticalLayout->addWidget(view);
}
MainWindow::~MainWindow()
{
delete ui;
}
附上效果图(小圆双击会变颜色):
源码下载地址1:https://github.com/RobinsonSir/QtDrawCircle.git
源码下载地址2:http://download.csdn.net/detail/zbc415766331/9043567
源码下载地址3:https://code.csdn.net/zbc415766331/qtdrawcircle
Qt坐标系参考文献:http://doc.qt.io/qt-4.8/graphicsview.html#the-graphics-view-coordinate-system