2

我正在尝试将鼠标按下事件链接到单击QLabel. 一些问题......当我传递一个 genericQWidget.mousePressEvent时,坐标只会显示第一次点击。当我尝试使鼠标事件特定于 aGraphicsScene(self.p1)时,出现以下错误:

Traceback (most recent call last):
  File "C:\Users\Tory\Desktop\DIDSONGUIDONOTCHANGE.py", line 59, in mousePressEvent
    self.p1.mousePressEvent(event)
TypeError: QGraphicsWidget.mousePressEvent(QGraphicsSceneMouseEvent): argument 1 has unexpected type 'QMouseEvent'

这是我正在使用的代码......我知道它已经关闭,但我对此很陌生,并且有点迷失从哪里开始。

def mousePressEvent(self, event):
    self.p1.mousePressEvent(event)
    x=event.x()
    y=event.y()
    if event.button()==Qt.LeftButton:
        self.label.setText("x=%0.01f,y=%0.01f" %(x,y))

如何让鼠标单击以显示图形场景 self.p1 的坐标?

4

1 回答 1

2

看起来事件过滤器可以做你想做的事。

这是一个简单的演示:

from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.scene = QtGui.QGraphicsScene(self)
        self.scene.addPixmap(QtGui.QPixmap('image.jpg'))
        self.scene.installEventFilter(self)
        self.view = QtGui.QGraphicsView(self)
        self.view.setScene(self.scene)
        self.label = QtGui.QLabel(self)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.view)
        layout.addWidget(self.label)

    def eventFilter(self, source, event):
        if (source is self.scene and
            event.type() == QtCore.QEvent.GraphicsSceneMouseRelease and
            event.button() == QtCore.Qt.LeftButton):
            pos = event.scenePos()
            self.label.setText('x=%0.01f,y=%0.01f' % (pos.x(), pos.y()))
        return QtGui.QWidget.eventFilter(self, source, event)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())
于 2012-08-24T22:21:03.463 回答