首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用QGraphicsItem ()限制itemChange

使用QGraphicsItem ()限制itemChange
EN

Stack Overflow用户
提问于 2017-11-10 05:54:05
回答 1查看 1.3K关注 0票数 3

我使用pyqt和Python3,我想防止QGraphicsRectItem在鼠标拖动时越过QGraphicsScene中的水平轴(y=0)。我使用下面的代码(使用height(),因为矩形位于屏幕的上半部分)。请参阅下面代码的完整示例。

代码语言:javascript
复制
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()

原则上,这是工作的,但当我继续拖动鼠标低于水平轴(y=0),矩形闪烁和跳跃之间的鼠标位置和它的约束位置在上半平面拖拽。因此,它看起来像是拖拽首先移动到鼠标光标,然后位置才会追溯调整。我希望在项目被移动(明显的)之前进行调整。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-01-03 17:17:20

您可以使用self.y() + self.rect().height() > 0测试该项是否仍然高于y轴。然而,self.y()指的是旧的/当前的位置。你应该用value.y()来测试新的职位。

因此,方法应该是:

代码语言:javascript
复制
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

请注意,如果测试通过,则返回value.x();如果测试失败,则调用超类的itemChange (就像itemChange Qt文档中的C++示例)。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47216468

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档