QGraphicsView的PyQt鼠标事件

QGraphicsView的PyQt鼠标事件,qt,pyqt,mouseevent,qgraphicsview,Qt,Pyqt,Mouseevent,Qgraphicsview,我试图从QGraphicsView中获取各种鼠标事件的坐标,但我不知道如何触发它们。最后,我想在graphicsView中添加一张图片,然后在上面绘制 理想情况下,我希望坐标在左上角有一个原点 0,0-------------------- | | | | | | | test.py import sys from PyQt4 import QtCore, QtGui, uic class test(QtGui.QMainWindow): def __init

我试图从QGraphicsView中获取各种鼠标事件的坐标,但我不知道如何触发它们。最后,我想在graphicsView中添加一张图片,然后在上面绘制

理想情况下,我希望坐标在左上角有一个原点

0,0--------------------
|
|
|
|
|
|
|          
test.py

import sys
from PyQt4 import QtCore, QtGui, uic


class test(QtGui.QMainWindow):

    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.ui = uic.loadUi('test.ui', self)

        self.connect(self.ui.graphicsView, QtCore.SIGNAL("mousePressEvent()"), self.mouse_pressed)
        self.connect(self.ui.graphicsView, QtCore.SIGNAL("mouseMoveEvent()"), self.mouse_moved)
        self.connect(self.ui.graphicsView, QtCore.SIGNAL("mouseReleaseEvent()"), self.mouse_released)

        self.ui.show()

    def mouse_pressed(self):
        p = QtGui.QCursor.pos()
        print "pressed here: " + p.x() + ", " + p.y()

    def mouse_moved(self):
        p = QtGui.QCursor.pos()
        print "moved here: " + p.x() + ", " + p.y()

    def mouse_released(self):
        p = QtGui.QCursor.pos()
        print "released here: " + p.x() + ", " + p.y()


def main():
    app = QtGui.QApplication(sys.argv)
    ui = test()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
test.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>800</width>
    <height>600</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <layout class="QVBoxLayout" name="verticalLayout">
    <item>
     <widget class="QGraphicsView" name="graphicsView"/>
    </item>
   </layout>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>800</width>
     <height>22</height>
    </rect>
   </property>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>

mousePressEvent
和其他方法都不是插槽。您不能在这些方法上使用
connect
。您需要在视图的
viewport()
上安装事件过滤器,并在小部件的
eventFilter
方法中捕获事件


请参阅。

要保持椭圆可移动,需要将事件传递给父级。例如,对于mouseMoveEvent,在方法末尾,您需要添加以下行:

super(graphicsScene, self).mouseMoveEvent(event)

我想你的意思是:“你不能在这些方法上使用
connect
”。此外,只覆盖
mousePressEvent()
比安装事件过滤器更容易、更干净。它需要OP来子类化
QGraphicsView
,并在UI文件中将视图升级到该子类。这是一种过度复杂化。如果想要更改视图的行为并在几个不同的地方重用该类,那么子类化
QGraphicsView
将是明智的。我想这在简单的情况下是不需要的。我想我已经按照你的建议做了。你知道为什么我的椭圆不能着色吗?
QColor.red
QColor.blue
是函数。您需要改用
Qt.red
Qt.blue
枚举值。我希望是最后一个问题。有没有简单的方法来保持椭圆的移动?
super(graphicsScene, self).mouseMoveEvent(event)