在这里,我开发了一个自定义小部件来打印一些形状。但是在这里我的 MouseRelease 和 MouseMove 事件不起作用。这是我的代码的问题。以及一些断言被执行。请帮我解决这个问题。
这是我的头文件
//painter.h
#ifndef PAINTER_H
#define PAINTER_H
#include <QWidget>
#include <QGraphicsView>
#include <math.h>
#include <QVector>
#include <QMouseEvent>
#include <QPoint>
class painter : public QWidget
{
Q_OBJECT
private:
enum Shape{CIRCLE,RECTENGEL,TRIANGEL} shape;
QGraphicsView *graphic;
QGraphicsScene *Scene;
QPoint *start;
QPoint *end;
QPen *pen;
QBrush *brush;
QVector<QGraphicsItem*> *items;
public:
explicit painter(QWidget *parent = 0);
void setSize(double width,double height);
void setShape(Shape value);
void addItem();
void clear();
void scale();
signals:
public slots:
protected:
void mousePressEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
};
#endif // PAINTER_H
这是我的 CPP 文件
//painter.cpp
#include "painter.h"
#include <QDebug>
#include <QGraphicsView>
#include <iterator>
painter::painter(QWidget *parent) :
QWidget(parent)
{
graphic = new QGraphicsView(this);
Scene = new QGraphicsScene(this);
pen = new QPen;
brush = new QBrush;
start = new QPoint;
end = new QPoint;
items = new QVector<QGraphicsItem*>();
graphic->setScene(Scene);
//Scene->addEllipse(10,10,50,50,*pen,*brush);//Scene->addLine(0,0,1,1);
// Scene->addRect(70,70,50,50,*pen,*brush);
graphic->setSceneRect(0,0,500,500);
Scene->addEllipse(20,20,20,20,*pen,*brush);
}
void painter::setSize(double width,double height)
{
graphic->setSceneRect(0,0,width,height);
}
void painter::setShape(Shape value)
{
if(value==CIRCLE)
shape = CIRCLE;
else if(value==RECTENGEL)
shape = RECTENGEL;
else if(value=TRIANGEL)
shape=TRIANGEL;
else
throw("Invalid Shape");
}
void painter::addItem()
{
QGraphicsItem *newItem;
double length = sqrt(pow((double)(start->x()-end->x()),2)+ pow((double)(start->y()-end->y()),2));
if(shape==TRIANGEL)
{
// QPolygonF triangel;
// triangel.
// Scene->addPolygon(,pen,brush);
}
else if(shape==RECTENGEL)
newItem = (QGraphicsItem*)Scene->addRect(end->x()-length,end->y()-length,2*length,2*length,*pen,*brush);
else
newItem = (QGraphicsItem*)Scene->addEllipse(end->x()-length,end->y()-length,2*length,2*length,*pen,*brush);
items->push_back(newItem);
}
void painter::clear()
{
for(int i=0;i<items->size();i++)
Scene->removeItem(items->at(i));
}
void painter::scale()
{
}
void painter::mousePressEvent(QMouseEvent *event)
{
end->setX(50);
end->setY(50);
start->setX(event->x());
start->setY(event->y());
shape = RECTENGEL;
addItem();
}
void painter::mouseMoveEvent(QMouseEvent *event)
{
qDebug("move");
}
void painter::mouseReleaseEvent(QMouseEvent *event)
{
end->setX(event->x());
end->setY(event->y());
addItem();
}