In my view there are 3 lines. 1 Polyline, and 2 straight lines. I have named them as P1 and s1 and s2
I am not able to select s1 line. If I try to select it , P1 gets selected ( though I have not clicked on P1 )
Selection of p1 is also not sharp. If I clicked somewhere around P1 ( not on P1 ) still P1 gets selected.
void Widget::on_designButoon_clicked()
{
// For straight line S2
QPolygon net0;
net0 << QPoint(50,180);
net0 << QPoint(600,180);
MyPoly* _poly0 = new MyPoly();
_poly0->DrawPolyline(net0,scene);
scene->addItem(static_cast<QGraphicsPathItem*>(_poly0));
// Same logic for Line S1 and P1
}
MyPoly.h
class MyPoly : public QGraphicsPathItem
{
//Q_OBJECT
public:
explicit MyPoly();
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
void DrawPolyline(QPolygon polygon);
private:
QPolygon polygon_;
};
MyPoly.cpp
MyPoly::MyPoly()
{}
void MyPoly::DrawPolyline(QPolygon polygon)
{
this->polygon_ = polygon;
QPainterPath pPath;
pPath.addPolygon(polygon);
this->setPen(QPen(QColor("blue"), 2));
this->setPath(pPath);
this->setFlag(QGraphicsItem::ItemIsSelectable);
}
void MyPoly::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
QWidget *widget)
{
auto copied_option = *option;
copied_option.state &= ~QStyle::State_Selected;
auto selected = option->state & QStyle::State_Selected;
QGraphicsPathItem::paint(painter, &copied_option, widget);
if (selected) {
painter->save();
painter->setBrush(Qt::NoBrush);
painter->setPen(QPen(option->palette.windowText(), 0, Qt::SolidLine));
if(contains(currentCursorPos))
painter->drawPath(shape());
painter->restore();
}
}
bool MyPoly::contains(const QPointF &point) const
{
for(int i=0;i < polygon_.count() - 1; i++)
{
QPointF firstPoint = polygon_.at(i);
QPointF lastPoint = polygon_.at(i+1);
if(firstPoint.x() == lastPoint.x())
{
qDebug()<<"Inside vertical line ";
//It is a vertical line
if(firstPoint.x() == point.x() &&
point.y() >= firstPoint.y() && point.y() <= lastPoint.y())
return true;
}
else
{
// it is a horizontal line
if(point.x() >= firstPoint.x() && point.x() <= lastPoint.x() &&
(firstPoint.y() - 3 <= point.y()) && (point.y() <= lastPoint.y() + 3 ))
return true;
}
}
return false;
}