4

我正在使用 PyQt 开发一个程序并创建一个小部件,该小部件显示一个网格和该网格上的一组多边形,您可以四处移动并单击它们。当我尝试实现多边形的单击时,它似乎不起作用。以下是不起作用的功能:

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)

对于上下文,self.polys是一个列表,QPolygons并且e.pos()是鼠标位置。我试过输入

print(poly)
print(poly.contains(QPoint(1,1)))

测试它是否适用于控制点,但在控制台中,它只给了我这个:

<PySide.QtGui.QPolygon(QPoint(50,350) QPoint(50,0) QPoint(0,0) QPoint(0,350) )  at 0x000000000547D608>
False

我在这里做错了什么,或者我怎样才能将上面的“多边形”转换为QPolygon我可以使用的实际?

编辑:

这是用于生成列表的代码self.polys

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

QPolygons使用内联 for 循环将其添加到列表中可能会出现问题吗?

4

1 回答 1

7

The reason this is not working is because bool QPolygon.contains( QPoint ) 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 QPoint(0,0), QPoint(0,200), or anything that does match either of those criteria.

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 QPolygon.containsPoint ( QPoint , Qt.FillRule ). 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: https://doc.qt.io/archives/qtjambi-4.5.2_01/com/trolltech/qt/core/Qt.FillRule.html

corrected code:

print(poly)
print(poly.containsPoint(QPoint(1,1), Qt.OddEvenFill))
于 2016-10-18T06:27:29.983 回答