pythonpyqt5qpolygon

Get the points of the QPolygonF


I have 3x QPolygonFs drawn on the screen, and I would need to calculate how much of the length of one QPolygon is inside the other. To illustrate, the percentage length of the red or blue polygon that is inside the black polygon: the % of the purple line that is inside the black polygon.

enter image description here

As I don't have the purple line itself, I believe that I should calculate it by taking the values of the red and blue polygon on every Y coordinate that it passes, and take the middle point of the two.

However I am not sure what is the best way to do so: I'd like to transform the QPolygonF itself to a series of coordinates, and then use Shapely Geometry as instructed in this answer to calculate the lines: Python - Return y coordinates of polygon path given x

Edit: It is important to mention, that I would need to have all the exterior coordinates of these polygons, not just the corner points defining them (all the points on the red line)

The Polygons were added as

drawn_polygon = {}     
all_polygon_corner_coords = {}
all_polygon_corner_coords["polygon1"] = [QPointF(x,y), ... , QPointF(xn,yn)]
drawn_polygon["polygon1"] = self.ImageDisplayQgraphicsView.scene().QPolygonF(all_polygon_corner_coords.get("polygon1")]

Is there any function in PyQt5 that would enable me to transform QPolygonF into the underlying coordinates? Or is there a simpler way to approach this problem?


Solution

  • If you want to obtain the vertices of the QPolygonF then you only have to iterate over it since it is a QVector.

    from PyQt5.QtCore import QPointF
    from PyQt5.QtGui import QPolygonF
    
    
    def main():
        poly = QPolygonF([QPointF(1, 1), QPointF(0, 10), QPointF(10, 10), QPointF(10, 0)])
    
        points = [poly[i] for i in range(poly.size())]
        print(points)
    
    
    if __name__ == "__main__":
        main()
    

    Output:

    [PyQt5.QtCore.QPointF(1.0, 1.0), PyQt5.QtCore.QPointF(0.0, 10.0), PyQt5.QtCore.QPointF(10.0, 10.0), PyQt5.QtCore.QPointF(10.0, 0.0)]
    

    Update:

    You cannot obtain all the points of the polygon since they are infinite, but you can map some of them and for this you can use QPainterPath:

    from PyQt5.QtCore import QPointF
    from PyQt5.QtGui import QPolygonF, QPainterPath
    
    
    def map_n_points_of_polygon(polygon, n):
        path = QPainterPath()
        path.addPolygon(polygon)
        return [path.pointAtPercent(i / (n - 1)) for i in range(n)]
    
    
    def main():
        poly = QPolygonF([QPointF(1, 1), QPointF(0, 10), QPointF(10, 10), QPointF(10, 0)])
    
        points = map_n_points_of_polygon(poly, 100)
        print(points)
    
    
    if __name__ == "__main__":
        main()