本文介绍了为什么我的 QGraphicsItem 不可选?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我复制了一些代码片段并制作了我自己的版本.初始片段(我不再拥有)允许移动并选择一个 QgraphicsItem.我的修改版本允许移动,但不能选择.我做错了什么?
I copied some code snippets and made my own version of it. The initial snippet (which I don't have anymore) allowed to move and also select a QgraphicsItem. My modified version allows movement, but not selecting. What am I doing wrong?
#!d:/python27/python -u
import sys
from PyQt4 import QtGui, QtCore
class GraphicsItem(QtGui.QGraphicsItem):
#
# QtGui.QGraphicsItem always needs to override its two public abstract methods
# paint, boundingRect
#
def __init__(self, rect=None, parent=None):
super(GraphicsItem, self).__init__(parent)
self.setFlag(QtGui.QGraphicsItem.ItemIsMovable, True)
self.setFlag(QtGui.QGraphicsItem.ItemIsSelectable, True)
self.pen = QtGui.QPen(QtCore.Qt.SolidLine)
self.pen.setColor(QtCore.Qt.blue)
self.pen.setWidth(8)
self.brush = QtGui.QBrush(QtCore.Qt.red)
self.rect = QtCore.QRectF(rect[0], rect[1], rect[2], rect[3])
def mouseMoveEvent(self, event):
# move object
QtGui.QGraphicsItem.mouseMoveEvent(self, event)
def boundingRect(self):
return self.rect
def paint(self, painter, option, widget):
painter.setBrush(self.brush)
painter.setPen(self.pen)
painter.drawEllipse(self.rect)
class MyMainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MyMainWindow, self).__init__(parent)
width = 1000
height = 800
scene = QtGui.QGraphicsScene(-width/2, -height/2, width, height)
graphicsItem = GraphicsItem((-100, -100, 200, 200))
scene.addItem(graphicsItem)
view = QtGui.QGraphicsView()
# set QGraphicsView attributes
view.setRenderHints(QtGui.QPainter.Antialiasing |
QtGui.QPainter.HighQualityAntialiasing)
view.setViewportUpdateMode(QtGui.QGraphicsView.FullViewportUpdate)
view.setScene(scene)
self.setCentralWidget(view)
def keyPressEvent(self, event):
key = event.key()
if key == QtCore.Qt.Key_Escape:
sys.exit(QtGui.qApp.quit())
else:
super(GraphicsView, self).keyPressEvent(event)
def main():
app = QtGui.QApplication(sys.argv)
form = MyMainWindow()
form.setGeometry(700, 100, 1050, 850)
form.show()
app.exec_()
if __name__ == '__main__':
main()
推荐答案
你在 GraphicsItem 类中错过了这个方法:
You miss this method in class GraphicsItem:
def mousePressEvent(self, event):
# select object
QtGui.QGraphicsItem.mousePressEvent(self, event)
print (self) # show the selected item
这篇关于为什么我的 QGraphicsItem 不可选?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!