Finding if a QPolygon contains a QPoint - Not giving expected results
<p>I am working on a program in PyQt and creating a widget that displays a grid and a set of polygons on that grid that you are able to move around and click on. When I try to implement the clicking of the polygon, it does not seem to work. Below is the function that does not work: </p>

<pre><code>def mouseMoveCustom(self, e):
    for poly in reversed(self.polys):
        if poly.contains(e.pos()):
            self.cur_poly = poly
            self.setCursor(Qt.PointingHandCursor)
            print('mouse cursor in polygon')
            break
        else:
            self.setCursor(Qt.CrossCursor)
</code></pre>

<p>For context, <code>self.polys</code> is a list of <code>QPolygons</code> and <code>e.pos()</code> is the mouse position. I have tried entering </p>

<pre><code>print(poly)
print(poly.contains(QPoint(1,1)))
</code></pre>

<p>to test if it would work for a control point, but in the console, it only gives me this:</p>

<pre><code>&lt;PySide.QtGui.QPolygon(QPoint(50,350) QPoint(50,0) QPoint(0,0) QPoint(0,350) )  at 0x000000000547D608&gt;
False
</code></pre>

<p>Is there something I am doing wrong here, or how can I convert the above "polygon" into an actual <code>QPolygon</code> that I can work with?</p>

<p><strong>EDIT:</strong></p>

<p>This is the code used to generate the list <code>self.polys</code>:</p>

<pre><code>self.polys.append(QPolygon([QPoint(points[i][X]+self.transform[X], points[i][Y]+self.transform[Y]) for i in range(len(points))]))
</code></pre>

<p>Could it perhaps be a problem with using an inline for loop to add the <code>QPolygons</code> to the list?</p>

<p>The reason this is not working is because bool <code>QPolygon.contains( QPoint )</code> returns true if the point is one of the vertices of the polygon, or if the point falls on the edges of the polygon. Some examples of points that would return true with your setup would be <code>QPoint(0,0)</code>, <code>QPoint(0,200)</code>, or anything that does match either of those criteria.</p>

<p>What you are looking for, presumably, is a function that returns true if the point resides within the polygon, rather than on it. The function you are looking for is <code>QPolygon.containsPoint ( QPoint , Qt.FillRule )</code>. The point is as you think it is, and the second value is either a 1 or a 0 (represented as either Qt.OddEvenFill or Qt.WindingFill respectively), which determine what method of finding whether or not a point is inside a polygon. Information about Qt.FillRule can be found here: <a href="https://doc.qt.io/archives/qtjambi-4.5.2_01/com/trolltech/qt/core/Qt.FillRule.html" rel="nofollow">https://doc.qt.io/archives/qtjambi-4.5.2_01/com/trolltech/qt/core/Qt.FillRule.html</a></p>

<p>corrected code:</p>

<pre><code>print(poly)
print(poly.containsPoint(QPoint(1,1), Qt.OddEvenFill))
</code></pre>

python pyqt qpolygon