使用itemChange()限制PyQt4中的项

时间:2015-12-20 09:16:35

标签: qt python-2.7 pyqt

我尝试使用Qt文档examplerectangle限制在场景区域但仍然失败,有人可以选择这样做吗?

我的代码,QGraphicsView实例是在Qt Desginer中创建的:

# -*- coding: utf-8 -*-

from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
from screen import *

class MovableItem(QGraphicsRectItem):
    def __init__(self, rectang, *args, **kwargs):
        QGraphicsRectItem.__init__(self, rectang, *args, **kwargs)
        self.setFlags(QGraphicsItem.ItemIsMovable |
                  QGraphicsItem.ItemSendsGeometryChanges)

        self.pen = QPen(Qt.darkMagenta)
        self.pen.setWidth(4)

        self.setPen(self.pen)

    def itemChange(self, change, value):
        if change == QGraphicsItem.ItemPositionChange and self.scene():
            # value is the new position.
            self.newPos = value.toPointF()
            self.rect = self.scene().sceneRect()

            if not(self.rect.contains(self.newPos)):
            # Keep the item inside the scene rect.
                self.newPos.setX(min(self.rect.right(), max(self.newPos.x(), self.rect.left())))
                self.newPos.setY(min(self.rect.bottom(), max(self.newPos.y(), self.rect.top())))

                return self.newPos

        return QGraphicsRectItem.itemChange(self, change, value)


class Main(QWidget, Ui_Form):
    def __init__(self, parent=None):
        super(Main, self).__init__(parent)
        self.setupUi(self)

        self.scene = QGraphicsScene()
        self.cena.setScene(self.scene)
        self.scene.addPixmap(QPixmap("01.png"))

        self. graph = MovableItem(2, 2, 300, 150)

        self.scene.addItem(self.graph)

    def showEvent(self, event):
        self.cena.fitInView(self.scene.sceneRect(), Qt.IgnoreAspectRatio)


app = QApplication(sys.argv)
window = Main()
window.show()

sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:1)

首先:

在主Main()中使用setSceneRect()来设置场景的大小。

第二

实际上,文档的示例是错误的,因此,要将矩形调整到场景,请删除此if并在min中减去参数right和{{1 } bottomright中的矩形尺寸bottomsetX。替换这部分代码:

setY

有关:

if not(self.rect.contains(self.newPos)):
# Keep the item inside the scene rect.
    self.newPos.setX(min(self.rect.right(), max(self.newPos.x(), self.rect.left())))
    self.newPos.setY(min(self.rect.bottom(), max(self.newPos.y(), self.rect.top())))

    return self.newPos