我正在将一个更大的QGraphicsItems程序转换为QGraphicsWidgets(让我们称它们为item和widget,以便打字)。鼠标悬停现在失败,因为小部件的位置和/或矩形与旧项目不同。我已经归结为一个简单的案例,包括视图,场景,项目和小部件。蓝色项目呈现100x50像素,并且hoverEnterEvent按预期发生。但是,红色小部件以半个预期宽度呈现。我可以解决这个问题,如果我为小部件重新实现纯虚函数boundingRect但是仍然只在50x50左半部分触发悬停事件。我需要使用/覆盖什么pos / rect /几何方法来使小部件与项目一样正确地与鼠标交互?谢谢。这是我的示例代码
#!/usr/local/bin/python
import os, sys
from PyQt4.Qt import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class MyView(QGraphicsView):
def __init__(self):
QGraphicsView.__init__(self)
self.setWindowFlags(Qt.WindowStaysOnTopHint)
self.scene = QGraphicsScene(self)
self.item = GraphicsItem('item', 100, 50)
self.item.moveBy(50, 50)
self.scene.addItem(self.item)
self.widget = GraphicsWidget('widget', 100, 50)
self.scene.addItem(self.widget)
self.setScene(self.scene)
class GraphicsItem(QGraphicsItem):
def __init__(self, name, width, height):
QGraphicsItem.__init__(self)
self.setAcceptHoverEvents(True)
self.name = name
self.__width = width
self.__height = height
def boundingRect(self):
return QRectF(0, 0, self.__width, self.__height)
def hoverEnterEvent(self, event):
self.__printGeometryDetails()
def paint(self, painter, option, widget):
bgRect = self.boundingRect()
painter.drawRects(bgRect)
painter.fillRect(bgRect, QColor('blue'))
def __printGeometryDetails(self):
print self.name
print ' pos (%.0f, %0.0f)' % (self.pos().x(), self.pos().y())
print ' boundingRect (%.0f, %0.0f, %.0f, %0.0f)' % (self.boundingRect().x(), self.boundingRect().y(), self.boundingRect().width(), self.boundingRect().height())
class GraphicsWidget(QGraphicsWidget):
def __init__(self, name, width, height):
QGraphicsWidget.__init__(self)
self.setAcceptHoverEvents(True)
self.name = name
self.__width = width
self.__height = height
def boundingRect(self):
return QRectF(0, 0, self.__width, self.__height)
def hoverEnterEvent(self, event):
self.__printGeometryDetails()
def paint(self, painter, option, widget):
bgRect = self.boundingRect()
painter.drawRects(bgRect)
painter.fillRect(bgRect, QColor('red'))
def __printGeometryDetails(self):
print self.name
print ' pos (%.0f, %0.0f)' % (self.pos().x(), self.pos().y())
print ' boundingRect (%.0f, %0.0f, %.0f, %0.0f)' % (self.boundingRect().x(), self.boundingRect().y(), self.boundingRect().width(), self.boundingRect().height())
print ' geometry (%.0f, %0.0f, %.0f, %0.0f)' % (self.geometry().x(), self.geometry().y(), self.geometry().width(), self.geometry().height())
print ' rect (%.0f, %0.0f, %.0f, %0.0f)' % (self.rect().x(), self.rect().y(), self.rect().width(), self.rect().height())
if __name__ == '__main__':
app = QApplication(sys.argv)
view = MyView()
view.setGeometry(600, 100, 400, 370)
view.show()
sys.exit(app.exec_())
答案 0 :(得分:5)
如果您使用self.resize(width, height)
而不是重新定义boundingRect
,它似乎可以正常工作。