qgraphicsitem 选中时颜色不一样
时间: 2023-12-31 19:05:20 浏览: 159
可以通过设置QGraphicsItem的选中状态来改变其颜色。可以通过以下步骤实现:
1. 在QGraphicsItem的构造函数中设置itemIsSelectable属性为true:`setFlag(QGraphicsItem::ItemIsSelectable, true);`
2. 重写QGraphicsItem的paint方法,在其中判断item是否被选中,如果被选中,则改变其颜色:
```
void MyItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
if (option->state & QStyle::State_Selected)
{
painter->setBrush(Qt::red);
}
else
{
painter->setBrush(Qt::green);
}
painter->drawRect(rect());
}
```
这样,当QGraphicsItem被选中时,其颜色会变为红色,否则为绿色。
相关问题
qgraphicsitem 选中时文字颜色不一样
类似于改变QGraphicsItem的颜色,可以通过重写QGraphicsItem的paint方法来改变其文字的颜色。可以通过以下步骤实现:
1. 在QGraphicsItem的构造函数中设置itemIsSelectable属性为true:`setFlag(QGraphicsItem::ItemIsSelectable, true);`
2. 重写QGraphicsItem的paint方法,在其中判断item是否被选中,如果被选中,则改变其文字的颜色:
```
void MyItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
if (option->state & QStyle::State_Selected)
{
painter->setPen(Qt::red);
}
else
{
painter->setPen(Qt::black);
}
painter->drawText(rect(), Qt::AlignCenter, "Hello World!");
}
```
这样,当QGraphicsItem被选中时,其文字的颜色会变为红色,否则为黑色。
QGraphicsItem选中改变颜色
您可以通过重写 QGraphicsItem 的 paint() 函数来实现选中时改变颜色的效果。在 paint() 函数中,可以根据 item 是否被选中来设置不同的画刷和画笔,从而改变其颜色。具体实现可以参考 Qt 官方文档中 QGraphicsItem 的相关章节。
阅读全文
相关推荐
















