qt c++重写继承QGraphicsView QGraphicsItem选中并改变颜色
时间: 2023-05-17 20:05:14 浏览: 216
可以通过重写QGraphicsItem的paint()函数来改变选中时的颜色,具体实现可以参考以下代码:
```
class MyGraphicsItem : public QGraphicsItem
{
public:
MyGraphicsItem(QGraphicsItem *parent = nullptr) : QGraphicsItem(parent) {}
QRectF boundingRect() const override
{
return QRectF(0, 0, 100, 100);
}
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override
{
if (option->state & QStyle::State_Selected)
{
painter->setPen(Qt::red);
painter->setBrush(Qt::red);
}
else
{
painter->setPen(Qt::black);
painter->setBrush(Qt::white);
}
painter->drawRect(boundingRect());
}
};
class MyGraphicsView : public QGraphicsView
{
public:
MyGraphicsView(QWidget *parent = nullptr) : QGraphicsView(parent)
{
setScene(new QGraphicsScene(this));
MyGraphicsItem *item = new MyGraphicsItem;
scene()->addItem(item);
}
protected:
void mousePressEvent(QMouseEvent *event) override
{
QGraphicsView::mousePressEvent(event);
QGraphicsItem *item = scene()->itemAt(mapToScene(event->pos()), transform());
if (item)
{
item->setSelected(true);
}
}
};
```
这里重写了MyGraphicsItem的paint()函数,在选中时将颜色设置为红色,未选中时设置为白色。在MyGraphicsView中重写了mousePressEvent()函数,当鼠标点击时获取当前位置的item并设置为选中状态。
阅读全文