QPainterPath - 移动/删除元素

Ste*_*Lee 3 python graphics qt pyside

有没有办法在QPainterPath中编辑单个'lineTo'元素的位置(或删除特定元素并用修改后的版本替换它们?).我尝试使用*.setElementPositionAt(i,x,y)无效(路径未重绘).

我基本上希望所有用户使用鼠标动态编辑折线的顶点(通过qpainterpath和lineTo方法创建).

显然,如果有更好的方法在QGraphicscene中创建折线,那么对此的一些建议也会受到欢迎.

Ava*_*ris 5

我不确定你是如何使用它setElementPositionAt但它的工作原理.诀窍QGraphicsSceneaddPath返回a QGraphicsPathItem,你需要QPainterPath使用其setPath方法更新该项目.

一个简单的例子:

import sys
from PySide import QtGui

class Widget(QtGui.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)

        self.view = QtGui.QGraphicsView()
        self.scene = QtGui.QGraphicsScene()
        self.scene.setSceneRect(0,0,100,100)
        self.view.setScene(self.scene)

        self.button = QtGui.QPushButton('Move path')
        self.button.clicked.connect(self.movePath)

        layout = QtGui.QHBoxLayout()
        layout.addWidget(self.view)
        layout.addWidget(self.button)

        self.setLayout(layout)

        self.createPath()

    def createPath(self):
        path = QtGui.QPainterPath()

        path.moveTo(25, 25)
        path.lineTo(25, 75)
        path.lineTo(75, 75)
        path.lineTo(75, 25)
        path.lineTo(25, 25)

        self.pathItem = self.scene.addPath(path)

    def movePath(self):
        # get the path
        path = self.pathItem.path()

        # change some elements
        # element 0: moveTo(25, 25)
        # element 1: lineTo(25, 75)
        # element 2: lineTo(75, 75)
        # ...
        path.setElementPositionAt(2, 90, 85)
        path.setElementPositionAt(3, 90, 15)

        # set the new path
        self.pathItem.setPath(path)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    main = Widget()
    main.show()

    sys.exit(app.exec_())
Run Code Online (Sandbox Code Playgroud)