2017-11-10 1 views
0

저는 pyqt와 Python 3을 사용하고 있습니다. QGraphicsRectItem이 마우스로 끌 때 QGraphicsRectItem이 가로 축 (y = 0)을 교차하지 않도록하고 싶습니다. 사각형이 화면의 위쪽에 있기 때문에 height()를 사용하여 다음 코드를 사용하고 있습니다. 아래 코드의 전체 예제를 참조하십시오. itemChange()를 사용하여 QGraphicsItem 유지하기

import sys 
from PyQt4.QtCore import Qt, QPointF 
from PyQt4.QtGui import QGraphicsRectItem, QGraphicsLineItem, QApplication, QGraphicsView, QGraphicsScene, QGraphicsItem 

class MyRect(QGraphicsRectItem): 
    def __init__(self, w, h): 
     super().__init__(0, 0, w, h) 
     self.setFlag(QGraphicsItem.ItemIsMovable, True) 
     self.setFlag(QGraphicsItem.ItemIsSelectable, True) 
     self.setFlag(QGraphicsItem.ItemIsFocusable, True) 
     self.setFlag(QGraphicsItem.ItemSendsGeometryChanges, True) 

    def itemChange(self, change, value): 
     if change == QGraphicsItem.ItemPositionChange: 
      if self.y() + self.rect().height() > 0: 
       return QPointF(self.x(), -self.rect().height()) 
     return value 

def main(): 
    # Set up the framework. 
    app = QApplication(sys.argv) 
    gr_view = QGraphicsView() 
    scene = QGraphicsScene() 
    scene.setSceneRect(-100, -100, 200, 200) 
    gr_view.setScene(scene) 

    # Add an x-axis 
    x_axis = QGraphicsLineItem(-100, 0, 100, 0) 
    scene.addItem(x_axis) 

    # Add the restrained rect. 
    rect = MyRect(50, 50) 
    rect.setPos(-25, -100) # <--- not clear to me why I have to do this twice to get the 
    rect.setPos(-25, -100) # item positioned. I know it has to do with my itemChanged above... 
    scene.addItem(rect) 

    gr_view.fitInView(0, 0, 200, 200, Qt.KeepAspectRatio)  
    gr_view.show() 
    sys.exit(app.exec_()) 

if __name__ == '__main__': 
    main() 

원칙적이 작동하지만, I가 수평축 아래 마우스 드래그 계속 (Y = 0), 직사각형 플리커가 앞뒤로 마우스 위치와 상부 hemiplane에서의 억제 위치 사이에서 이동 드래그하면서 그래서 끌기가 먼저 마우스 커서로 드래그 한 다음 그 위치 만 소급하여 조정 한 것처럼 보입니다. 항목을 이동하기 전에 (시각적으로) 조정을 수행하고 싶습니다.

+0

같은 끝쪽으로 mouseMoveEvent를 사용하면 아주 잘 작동합니다. 그것은 단순히 항목이 마우스 커서 아래의 항목에만 적용되기 때문에 항목 그룹을 선택할 때 실패합니다. – zeus300

+0

항목 이동을 제한하는 방법을 보여주는 [mcve]를 제공하십시오. – ekhumoro

+1

[QGraphicsItem 객체를 X 축을 통해서만 이동할 수 있습니다] (https://stackoverflow.com/questions/22881888/qgraphicsitem-move-object-only-through-x-axis) –

답변

2

self.y() + self.rect().height() > 0을 사용하면 항목이 여전히 y 축 위에 있는지 테스트 할 수 있습니다. 그러나 self.y()은 이전/현재 위치를 나타냅니다. 대신 value.y()으로 새 위치에서 테스트해야합니다.

그래서 방법은해야한다 : 나는 value.x()을 반환

def itemChange(self, change, value): 
    if change == QGraphicsItem.ItemPositionChange: 
     if value.y() + self.rect().height() > 0: 
      return QPointF(value.x(), -self.rect().height()) 
    return super().itemChange(change, value) # Call super 

참고 테스트가 실패하면 테스트에 통과하면와 것은 (바로 itemChange Qt documentation의 C++ 예처럼) 슈퍼 클래스의 itemChange 전화

+0

완벽합니다. 그것은 또한 두 번해야했던 포지셔닝과 관련된 다른 문제를 해결합니다. – zeus300

관련 문제