Example of a User Drawn Line Segment using QPolygon as a select region

Get the Flash Player to see this video.

Download the complete project zip file

In this example, the user is able to move a line, grab either end and stretch and rotate the line. This type of line would be used in a drawing application.

The trick to this turns on providing a selection region around the line, so that the line can be highlighted when the user moves the the mouse close to the line. QGraphics items normally detect the mouse hover events when the mouse is within the bounding region, which is a rectangle. We can easily imagin a selection rectangle around a line if the line is horizontal or vertical, but if the line cuts an angle, the standard bounding region will not work.

The solution used in this example uses the QPolygonF class and the QGraphicsItem.setPolygon() method to define an arbitrary path, to define a selection region, no matter the angle or shape taken by the line. The corner points of the polygon are selected so that an area is created around each end of the line. As the user’s mouse moves near an end of the line, the bounding box defined by the polygon detects the mouse and passes this signal on to the line object (SelectableLineSegmentGraphic).

If the user selects the middle section of the line, the line’s position is moved, but its shape and orientation are not moved. If the user selects an end of the line, the line is re-drawn to meet the new mouse location, effectively changing the length and angle. Note, however, the position of the line object is not changed, only the appearance of the line pixels and and the bounding region are changed. The position of the line could end up being no where close to the bounding region, but this does not cause any issues.

picture of bounding box around the line segment

The code block below shows the calculations used to define a new bounding polygon around the new line, based on the most recent mouse-moved event and mouse position.

Leave a Reply

Trackback this post  |  Subscribe to the comments via RSS Feed