问题
https://www.dropbox.com/s/phven3rriv36893/graphicsview-pathitem.png?dl=0 I wonder if there's a way to make my QGraphicsPathItem respond to mouseHoverEvents to the actual curve instead of the whole orange area as seen in the docs.
https://www.dropbox.com/s/7m8w34nitp34sgf/pipes.png?dl=0 In my application I'm not seeing the area that actually forms the path and therefor I only want a hoverEnterEvent when the bezier curve is hovered (and a hoverLeaveEvent when the bezier is left of, course).
Is that possible to achieve with QGraphicsPathItem or is that a completely wrong approach? If yes, how? If not, what QGraphics object can be considered as a replacement?
If code is really needed, let me know.
Cheers, Michael
回答1:
You need to reimplement QGraphicsItem.shape
to return a more accurate representation of your curve. The default implementation gives you the bounding box as you've discovered.
回答2:
Tim Wakeham's answer is totally correct: you need to re-implement shape()
to provide a more detailed shape for your path item. However, his answer is not totally useful, since it's not trivial to implement a good shape()
method returning the right QPainterPath
.
It's even more confusing because in this case, the QGraphicsPathItem
can already provide a QPainterPath
from its path()
method. Unfortunately that is generally not the right value to return from the shape()
method since it draws the item rather than delimits its outside.
Fortunately, since this is a fairly standard requirement, there is a built-in class to transform the path into an outline that can be used for the shape: QPainterPathStroker
.
Here's some code I use to do that:
qp = QtGui.QPainterPathStroker()
qp.setWidth(MARGIN)
qp.setCapStyle(QtCore.Qt.SquareCap)
shape = qp.createStroke(self.path())
来源:https://stackoverflow.com/questions/32428810/qgraphicspathitem-hoverevents-suppress-hover-on-area-formed-by-the-path