要实现这个功能,需要在 QGraphicsView 中重写 mousePressEvent 和 keyPressEvent 方法,并使用 selectedItems() 方法获取当前选中的图形项。
以下是示例代码:
from PyQt5.QtWidgets import QApplication, QGraphicsScene, QGraphicsView, QGraphicsRectItem
from PyQt5.QtGui import QColor, QPen
from PyQt5.QtCore import Qt
class MyRectItem(QGraphicsRectItem):
def __init__(self, x, y):
super().__init__(x, y, 50, 50)
self.setFlag(QGraphicsRectItem.ItemIsSelectable)
def paint(self, painter, option, widget=None):
if self.isSelected():
pen = QPen(Qt.green)
else:
pen = QPen(Qt.blue)
painter.setPen(pen)
painter.drawRect(self.rect())
class MyView(QGraphicsView):
def mousePressEvent(self, event):
# Call the base class method to handle other events.
super().mousePressEvent(event)
# Get the list of selected items.
items = self.scene().selectedItems()
# Set the color of the selected item to green and all other items to blue.
for item in self.scene().items():
if item in items:
item.setSelected(True)
item.update()
else:
item.setSelected(False)
item.update()
def keyPressEvent(self, event):
# Call the base class method to handle other events.
super().keyPressEvent(event)
# Get the list of selected items.
items = self.scene().selectedItems()
# Set the color of the selected item to green and all other items to blue.
for item in self.scene().items():
if item in items:
item.setSelected(True)
item.update()
else:
item.setSelected(False)
item.update()
if __name__ == '__main__':
app = QApplication([])
scene = QGraphicsScene()
view = MyView(scene)
items = []
for i in range(3):
for j in range(3):
item = MyRectItem(i * 60 + 10, j * 60 + 10)
scene.addItem(item)
items.append(item)
view.show()
app.exec_()
在上面的示例中,我们创建了一个名为 MyView 的自定义视图类,它继承自 QGraphicsView。在 mousePressEvent 和 keyPressEvent 方法中,我们首先调用父类方法以处理其他事件。然后使用 selectedItems() 方法获取当前选中的图形项列表。
接下来,我们循环遍历场景中的所有图形项,并根据是否被选中来设置其边框颜色。如果该图形项被选中,则将其边框颜色设置为绿色;否则将其边框颜色设置为蓝色。
最后,在主程序中,我们创建了一个 3x3 的矩形项网格,并将它们添加到场景中。当用户点击鼠标或按下键盘时,选中的方块会变成绿色,其他方块会变成蓝色。