QT开发中文网

QGraphicsView 怎么选中一个方块就把它的边框颜色变成绿色 其他的方块变成蓝色 单词智能选中一个方块

要实现这个功能,需要在 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 的矩形项网格,并将它们添加到场景中。当用户点击鼠标或按下键盘时,选中的方块会变成绿色,其他方块会变成蓝色。

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://qt.0voice.com/?id=3051

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?