下面的代码显示了我尝试让几个可移动VerticalLineSegment
对象(派生自QGraphicsLineItem
and )在它们移动时QObject
向一个(使用 a )发出另一个信号。QSignalMapper
我很感激为什么没有触发VerticalLineSegment
插槽的帮助。updateX
(未来的目标是让VerticalLineSegment
s 在不同QGraphicsScene
的 s 中,但我认为现在最好保持简单。)
from PySide import QtGui, QtCore
import sys
class VerticalLineSegment( QtCore.QObject , QtGui.QGraphicsLineItem ):
onXMove = QtCore.Signal()
def __init__(self, x , y0 , y1 , parent=None):
QtCore.QObject.__init__(self)
QtGui.QGraphicsLineItem.__init__( self , x , y0 , x , y1 , parent)
self.setFlag(QtGui.QGraphicsLineItem.ItemIsMovable)
self.setFlag(QtGui.QGraphicsLineItem.ItemSendsGeometryChanges)
self.setCursor(QtCore.Qt.SizeAllCursor)
def itemChange( self , change , value ):
if change is QtGui.QGraphicsItem.ItemPositionChange:
self.onXMove.emit()
value.setY(0) # Restrict movements along horizontal direction
return value
return QtGui.QGraphicsLineItem.itemChange(self, change , value )
def shape(self):
path = super(VerticalLineSegment, self).shape()
stroker = QtGui.QPainterPathStroker()
stroker.setWidth(5)
return stroker.createStroke(path)
def boundingRect(self):
return self.shape().boundingRect()
# slot
def updateX(self , object ):
print "slot"
class CustomScene(QtGui.QGraphicsScene):
def __init__(self , parent=None):
super(CustomScene, self).__init__(parent)
self.signalMapper = QtCore.QSignalMapper()
def addItem( self , item ):
self.signalMapper.setMapping( item , item )
item.onXMove.connect(self.signalMapper.map )
self.signalMapper.mapped.connect(item.updateX)
return QtGui.QGraphicsScene.addItem(self,item)
class Editor(QtGui.QMainWindow):
def __init__(self, parent=None):
super(Editor, self).__init__(parent)
scene = CustomScene()
line0 = VerticalLineSegment( 10 , 210 , 300 )
line1 = VerticalLineSegment( 10 , 110 , 200 )
line2 = VerticalLineSegment( 10 , 10 , 100 )
scene.addItem( line0 )
scene.addItem( line1 )
scene.addItem( line2 )
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_())