首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >QMouseEvent,收到意外类型

QMouseEvent,收到意外类型
EN

Stack Overflow用户
提问于 2012-08-25 04:19:53
回答 1查看 2.3K关注 0票数 2

我正在尝试将鼠标按下事件链接到在QLabel中单击时显示鼠标的坐标。一些问题..。当我传递一个通用的QWidget.mousePressEvent时,坐标只会在第一次单击时显示。当我试图使鼠标事件特定于一个GraphicsScene(self.p1)时,我得到了以下错误:

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

这是我使用的代码..。我知道这是错误的,但我是个新手,不知道从哪里开始。

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-08-25 06:21:03

看起来event filter可以做你想做的事情。

下面是一个简单的演示:

代码语言:javascript
复制
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_())
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12116073

复制
相关文章

相似问题

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