我试图了解path1.subtracted(path2)
的工作原理。
我有路径1和路径2:
我正在使用path3=path1.subtracted(path2)
获取path3。
为什么我没有想要的道路?图片:
这是代码:
from PyQt5.QtCore import QPointF
from PyQt5.QtCore import QRectF, Qt
from PyQt5.QtGui import QPainterPath, QPen
from PyQt5.QtGui import QPolygonF
from PyQt5.QtWidgets import QApplication, QGraphicsScene, \
QGraphicsView, QPushButton, QWidget, \
QVBoxLayout, QGraphicsItem, QGraphicsPathItem, QGraphicsRectItem
class Window(QWidget):
scene = None
def __init__(self):
QWidget.__init__(self)
self.view = View(self)
self.button = QPushButton('Clear View', self)
self.button.clicked.connect(self.handleClearView)
layout = QVBoxLayout(self)
layout.addWidget(self.view)
layout.addWidget(self.button)
def handleClearView(self):
self.view.scene.clear()
class View(QGraphicsView):
def __init__(self, parent):
self.scribing = False
self.erasing = False
QGraphicsView.__init__(self, parent)
self.scene = QGraphicsScene()
self.setScene(self.scene)
def resizeEvent(self, QResizeEvent):
self.setSceneRect(QRectF(self.viewport().rect()))
def mousePressEvent(self, event):
if event.buttons() == Qt.LeftButton:
self.scribing = True
self.path1 = QPainterPath()
self.path2 = QPainterPath()
self.polygon1 = QPolygonF()
self.polygon1.append(QPointF(100,100))
self.polygon1.append(QPointF(100, 300))
self.polygon1.append(QPointF(300, 300))
self.polygon1.append(QPointF(300, 100))
self.polygon2 = QPolygonF()
self.polygon2.append(QPointF(300,100))
self.polygon2.append(QPointF(300, 300))
self.polygon2.append(QPointF(100, 300))
self.path1.addPolygon(self.polygon1)
self.path2.addPolygon(self.polygon2)
path3 = self.path1.subtracted(self.path2)
# self.scene.addPath(self.path1, QPen(Qt.blue))
# self.scene.addPath(self.path2, QPen(Qt.green))
self.scene.addPath(path3, QPen(Qt.red))
if event.buttons() == Qt.RightButton:
self.erasing = True
def mouseMoveEvent(self, event):
if (event.buttons() & Qt.LeftButton) and self.scribing:
if self.free_draw_item:
pass
if event.buttons() & Qt.RightButton and self.erasing:
pass
def mouseReleaseEvent(self, event):
self.scribing = False
self.erasing = False
# if self.eraser_item != None:
# self.scene.removeItem(self.eraser_item)
# if self.free_draw_item != None:
# self.free_draw_item.setSelected(True)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
window = Window()
window.resize(640, 480)
window.show()
sys.exit(app.exec_())
在此示例中,我正在使用
QPolygonF
。我也尝试创建p1=QPainterPath()
,p2=QPainterPath()
并减去以获得p3
。但是,没有成功,就无法获得相同的结果。 最佳答案
QpainterPath.subtracted()
不会减去路径元素,但会减去路径面积,
see documentation
如果使用QpainterPath::operator-()
,则具有相同的效果:
# path3 = self.path1.subtracted(self.path2)
path3 = self.path1 – self.path2
您可以通过类似这样的方式来识别路径的元素
c = path3.elementCount()
for i in range(c):
e = path3.elementAt(i)
print('Element-nr.: ', i, 'Type: ', e.type, 'x: ', e.x, 'y: ', e.y) # type: 0 = MoveTo, 1 = LineTo
我认为,您必须编写自己的方法,该方法根据path1和path2的元素创建path3。
关于python - 如何减去QPainterPaths,QPolygon?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39726477/