4

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に問題があると確信しています。しかし、戻って信号とスロットについて読むたびに、それは理にかなっていますが、私はそれを得ることができません。

助けてください、私はここ数日頭を叩いています。これが以前に尋ねられた場合は申し訳ありませんが、私はこのトピックに関するすべてのスレッドを通過し、どこにも到達できません。

ありがとう

4

1 に答える 1

3

シグナルはQGraphicsView、UIで定義されたオブジェクトから送信される必要があります。

QGraphicsViewこのように派生したクラスを作成できます

from PyQt4.QtCore import *
from PyQt4.QtGui import *

class MyView(QGraphicsView):
    moved = pyqtSignal(QMouseEvent)

    def __init__(self, parent = None):
        super(MyView, self).__init__(parent)

    def mouseMoveEvent(self, event):
        # call the base method to be sure the events are forwarded to the scene
        super(MyView, self).mouseMoveEvent(event)

        print "Mouse Pointer is currently hovering at: ", event.pos()
        self.moved.emit(event)

次に、デザイナーで:

  • 右クリックして、[昇格QGraphicsView]をクリックします
  • [プロモートクラス名]フィールドにクラス名を入力します(例:「MyView」)。
  • そのクラスがヘッダーファイルフィールドにあるが、拡張子が.pyでないファイル名を書き込み、
  • [追加]ボタンをクリックしてから、[プロモート]ボタンをクリックします。

そして、pyuic4を使用してファイルgui.pyを再生成できます。

于 2011-09-24T01:09:51.490 に答える