0

次の PyQt4 アプリの問題は、アイテムをドラッグするとアイテムが移動しすぎることです。実際にマウス ポインターを移動する量が 2 倍になるため、アイテムをキャンバス上でドラッグしている間、一方向に「十分に移動」した後、マウス ポインターはアイテムのバウンディング ボックスの外に出ます。

私は何を間違っていますか?ご覧のとおり、私は大きなものをオーバーライドしていません。

メインウィンドウ:

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 に答える