QGraphicsViewと相互作用するプログラムを作成しようとしています。QGraphicsViewで発生したときに、マウスとキーボードのイベントを収集したいと思います。たとえば、ユーザーがQGraphicsViewウィジェットをクリックすると、マウスの位置が表示されます。かなり簡単にハードコーディングできますが、UIが頻繁に変更されるため、QtDesignerを使用したいと思います。
これは私がgui.pyのために持っているコードです。QGraphicsViewを含むシンプルなウィジェット。
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_graphicsViewWidget(object):
def setupUi(self, graphicsViewWidget):
graphicsViewWidget.setObjectName(_fromUtf8("graphicsViewWidget"))
graphicsViewWidget.resize(400, 300)
graphicsViewWidget.setMouseTracking(True)
self.graphicsView = QtGui.QGraphicsView(graphicsViewWidget)
self.graphicsView.setGeometry(QtCore.QRect(70, 40, 256, 192))
self.graphicsView.setObjectName(_fromUtf8("graphicsView"))
self.retranslateUi(graphicsViewWidget)
QtCore.QMetaObject.connectSlotsByName(graphicsViewWidget)
def retranslateUi(self, graphicsViewWidget):
graphicsViewWidget.setWindowTitle(QtGui.QApplication.translate("graphicsViewWidget", "Form", None, QtGui.QApplication.UnicodeUTF8))
プログラムのコード:
#!/usr/bin/python -d
import sys
from PyQt4 import QtCore, QtGui
from gui import Ui_graphicsViewWidget
class MyForm(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_graphicsViewWidget()
self.ui.setupUi(self)
QtCore.QObject.connect(self.ui.graphicsView, QtCore.SIGNAL("moved"), self.test)
def mouseMoveEvent(self, event):
print "Mouse Pointer is currently hovering at: ", event.pos()
self.emit(QtCore.SIGNAL("moved"), event)
def test(self, event):
print('in test')
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = MyForm()
myapp.show()
sys.exit(app.exec_())
このコードを実行すると、私が望むものとは逆になります。QGraphicsView内を除いて、どこでもマウスの位置を取得します。
QObject.connectに問題があると確信しています。しかし、戻って信号とスロットについて読むたびに、それは理にかなっていますが、私はそれを得ることができません。
助けてください、私はここ数日頭を叩いています。これが以前に尋ねられた場合は申し訳ありませんが、私はこのトピックに関するすべてのスレッドを通過し、どこにも到達できません。
ありがとう