使 QGraphicsLineItem 不那么繁琐地拖动

Making QGraphicsLineItem less fiddly to drag

如下所示,我创建了一个可拖动的 QGraphicsLineItem。但问题是选择线路非常繁琐。我想增加线的 "selection radius" 以便更容易拖动

from PySide import QtGui, QtCore
import sys

class VerticalLine(QtGui.QGraphicsLineItem):
    def __init__(self, x , y0 , y1 , parent=None):
        super(VerticalLine, self).__init__(x , y0 , x , y1 , parent)
        self.setFlag(QtGui.QGraphicsLineItem.ItemIsMovable)
        self.setFlag(QtGui.QGraphicsLineItem.ItemSendsGeometryChanges)
        self.setCursor(QtCore.Qt.SizeAllCursor) 


class Editor(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(Editor, self).__init__(parent)

        line = VerticalLine( 10 , 10 , 100 )
        scene = QtGui.QGraphicsScene()
        scene.addItem( line )
        view = QtGui.QGraphicsView()
        view.setScene( scene )

        self.setGeometry( 250 , 250 , 600 , 600 )
        self.setCentralWidget(view)
        self.show()

if __name__=="__main__":
    app=QtGui.QApplication(sys.argv)
    myapp = Editor()
    sys.exit(app.exec_()) 

您必须重写 shape() 和 boundingRect() 方法,以便它们 return 一个更大的区域,为此使用 QPainterPathStroker 以线为基础创建一个区域并确定宽度.

class VerticalLine(QtGui.QGraphicsLineItem):
    def __init__(self, x , y0 , y1 , parent=None):
        super(VerticalLine, self).__init__(x , y0 , x , y1 , parent)
        self.setFlag(QtGui.QGraphicsLineItem.ItemIsMovable)
        self.setFlag(QtGui.QGraphicsLineItem.ItemSendsGeometryChanges)
        self.setCursor(QtCore.Qt.SizeAllCursor) 

    def shape(self):
        path = super(VerticalLine, self).shape()
        stroker = QtGui.QPainterPathStroker()
        stroker.setWidth(20)
        return stroker.createStroke(path)

    def boundingRect(self):
        return self.shape().boundingRect()