使QGraphicsLineItem不太容易拖动

时间:2019-04-04 08:10:22

标签: python pyside qgraphicsview qgraphicsscene qgraphicslineitem

如下所示,我创建了一个可拖动的QGraphicsLineItem。但是,问题在于选择线是很麻烦的。我想增加线条的“选择半径”,以使其更容易拖动

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_()) 

1 个答案:

答案 0 :(得分:1)

您必须覆盖shape()和boundingRect()方法,以便它们返回更大的区域,为此,使用了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()