Drawing polygon using event filter in Qt
-
I am working on a feature in my GUI that allow user to draw polygon by clicking the points.
First the user needs to enable this function by clicking a button. After that the user clicks any four points on the screen. When the fourth point is clicked, all the 4 points will be connected to form a polygon.However the polygon is not appearing after the fourth is clicked. Instead there is a message of "QPainter::begin: Paint device returned engine == 0, type: 1". What is the problem in my code?
@bool QTGraphicsShape::eventFilter(QObject *obj, QEvent *event)
{
double static x[4],y[4];
int static i;
if ((event->type() == QEvent::GraphicsSceneMouseRelease) && (Draw3Points == true)) {
QGraphicsSceneMouseEvent mouseEvent = static_cast< QGraphicsSceneMouseEvent >( event );
QPointF img_coord_pt = mouseEvent->scenePos();
x[i] = img_coord_pt.x();
y[i] = img_coord_pt.y();
i++;
if (i >= 4)
{
Draw3Points = false;
i=0;
static const QPointF points[4] = {
QPointF(x[0], y[0]),
QPointF(x[1], y[1]),
QPointF(x[2], y[2]),
QPointF(x[3], y[3])
};
QPainter painter(this);
painter.drawPolygon(points, 4);
}
return true;
} else {
return QObject::eventFilter(obj, event);
}
}void QTGraphicsShape::on_pushButton_clicked()
{
ui.graphicsView->setMouseTracking(true);
Draw3Points = true;
m_pGraphicsScene->installEventFilter(this);
}@ -
Any reason you are using eventFilter for this. Event filter is not the right place for you to draw. Either you use paint or paintEvent(..) method make this happen.
-
Hi,
I have reimplemented paint method to draw a polygon like this.@
void OverlayPolygon::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *)
{
qDebug() << "OverlayPolygon->paint";
QPen p(colorBG);
p.setColor(colorBG);
p.setStyle(penStyle);
p.setWidth(lineWidth);
p.setBrush(colorBG);// polyPoints is a QList<QPointF*> QPointF pointArr[polyPoints.size()]; for(int i = 0; i < polyPoints.size(); i++){ pointArr[i].setX(polyPoints.at(i)->x()); pointArr[i].setY(polyPoints.at(i)->y()); } painter->setPen(p); painter->drawConvexPolygon(pointArr, polyPoints.size());
}
@
First collect all points and then pass them to painter in reimplemented paint method.
Hope it helps...