0

以下 PyQt4 应用程序的问题是,当我拖动它们时,它移动了太多项目 - 是我实际移动鼠标指针的两倍,所以当我在画布上拖动项目时,在一个方向“足够移动”之后,鼠标指针最终位于项目的边界框之外。

我究竟做错了什么?如您所见,我并没有压倒任何大的东西:

主窗口:

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from grapheditor.ui_mainwindow import Ui_MainWindow
from grapheditor.customwidgets import GraphViewer
from grapheditor.graphholder import GraphHolder
from grapheditor.graphnode import GraphNode

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.showMaximized()
        QTimer.singleShot(0, self.setup)
    def setup(self):
        self.scene = GraphHolder()
        self.ui.graphicsView.setScene(self.scene)
        #self.ui.graphicsView.setSceneRect(0, 0, 1500, 1500)
        self.drawItems()
    def drawItems(self):
        QGraphicsLineItem(0, -10, 0, 1000, None, self.scene)
        QGraphicsLineItem(-10, 0, 1000, 0, None, self.scene)
        item = GraphNode("hello", 0, 0, 30, 40)
        self.scene.addItem(item)

    def getCanvas(self):
        return self.ui.graphicsView

风景

from PyQt4.QtGui import *
from PyQt4.QtCore import *

class GraphViewer(QGraphicsView):
    def __init__(self, parent=None):
        super(GraphViewer, self).__init__(parent)
        self.setInteractive(True)

项目

from PyQt4.QtCore import *
from PyQt4.QtGui import *

class GraphNode(QGraphicsItem):
    penWidth = 2
    cornerRadius = 10
    def __init__(self, ident, x, y, width, height, parent=None):
        super(GraphNode, self).__init__(parent)
        self.ident = ident
        self.setPos(x, y)
        self.width = width
        self.height = height
        self.setFlags(QGraphicsItem.ItemIsMovable|QGraphicsItem.ItemIsSelectable)

    def boundingRect(self):
        return QRectF(self.pos().x() - self.penWidth / 2, self.pos().y() - self.penWidth / 2,self.width + self.penWidth, self.height + self.penWidth)

    def paint(self, painter, optiongraphicsitem, widget):
         painter.drawRoundedRect(self.pos().x(), self.pos().y(), self.width, self.height, self.cornerRadius, self.cornerRadius)
         painter.drawRect(self.boundingRect())

场景现在只是一个空类:

from PyQt4.QtCore import *
from PyQt4.QtGui import *

class GraphHolder(QGraphicsScene):
    def __init__(self, parent=None):
        super(GraphHolder, self).__init__(parent)
4

1 回答 1

1

您的实施boundingRect不正确。boundingRect应该返回项目坐标系中的坐标。场景会将项目位置添加到边界矩形以计算实际项目位置。边界矩形不能依赖于self.pos(). 在您的情况下,此错误会导致项目的重复添加和错误定位。正确实现:

def boundingRect(self):
  return QRectF(-self.penWidth / 2, -self.penWidth / 2, 
                self.width + self.penWidth, self.height + self.penWidth)
于 2013-11-01T11:01:28.553 回答