在Qt中,要改变QGraphicsRectItem
在被点击时的填充颜色,你可以重写mousePressEvent
方法来处理鼠标点击事件,并在其中改变矩形的填充颜色。以下是一个示例代码,展示了如何实现这一功能:
#include <QGraphicsRectItem>
#include <QGraphicsSceneMouseEvent>
class ClickableRectItem : public QGraphicsRectItem {
public:
ClickableRectItem(const QRectF &rect, QGraphicsItem *parent = nullptr)
: QGraphicsRectItem(rect, parent), fillColor(Qt::white) {
setAcceptHoverEvents(true); // 可选,如果你还想处理悬停事件
}
protected:
void mousePressEvent(QGraphicsSceneMouseEvent *event) override {
if (event->button() == Qt::LeftButton) {
// 切换填充颜色
fillColor = fillColor == Qt::white ? Qt::green : Qt::white;
update(); // 更新项目以触发重绘
}
QGraphicsRectItem::mousePressEvent(event); // 调用基类的事件处理器
}
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) override {
QPen pen(Qt::black); // 边框颜色
pen.setWidth(1); // 边框宽度
painter->setPen(pen);
painter->setBrush(fillColor); // 设置填充颜色
painter->drawRect(rect()); // 绘制矩形
}
private:
QColor fillColor;
};
在这个例子中,ClickableRectItem
类有一个私有成员 fillColor
,它用于存储矩形的当前填充颜色。在构造函数中,填充颜色被初始化为白色。当鼠标左键点击该矩形时,mousePressEvent
方法会被调用,并切换 fillColor
的值。如果当前颜色是白色,则将其更改为绿色;如果是绿色,则将其更改回白色。然后,通过调用 update()
方法触发重绘事件。
在 paint
方法中,使用 QPainter
设置笔和刷子来绘制矩形。笔用于绘制边框,而刷子用于填充矩形内部。
要使用这个自定义矩形项,你可以像之前一样创建它并将其添加到场景中:
QGraphicsScene *scene = new QGraphicsScene();
ClickableRectItem *rectItem = new ClickableRectItem(QRectF(0, 0, 100, 100));
scene->addItem(rectItem);
现在,每当你点击这个矩形项时,它的填充颜色就会在白色和绿色之间切换。