在Qt中,如果你想要在点击QGraphicsRectItem
时改变其边框颜色,你可以通过重写mousePressEvent
函数来实现这一功能。下面是一个简单的例子,展示了如何在点击时改变边框颜色:
#include <QGraphicsRectItem>
#include <QGraphicsSceneMouseEvent>
class ClickableRectItem : public QGraphicsRectItem {
public:
ClickableRectItem(const QRectF &rect, QGraphicsItem *parent = nullptr)
: QGraphicsRectItem(rect, parent) {
// 初始化边框颜色
borderColor = Qt::black;
setAcceptHoverEvents(true); // 启用悬停事件,如果需要的话
}
protected:
void mousePressEvent(QGraphicsSceneMouseEvent *event) override {
if (event->button() == Qt::LeftButton) {
// 点击时改变边框颜色
borderColor = Qt::red; // 或者任何你想要的颜色
update(); // 更新以触发重绘
}
QGraphicsRectItem::mousePressEvent(event); // 调用基类的mousePressEvent
}
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) override {
QPen pen(borderColor);
pen.setWidth(2); // 设置边框宽度
painter->setPen(pen);
painter->setBrush(Qt::white); // 设置矩形内部填充颜色,可以根据需要修改
painter->drawRect(rect()); // 绘制矩形
}
private:
QColor borderColor;
};
在这个例子中,ClickableRectItem
类继承自QGraphicsRectItem
。当鼠标左键点击该矩形项时,mousePressEvent
函数会被触发,并将边框颜色改为红色。然后调用update()
函数来触发一个重绘事件,这会导致paint
函数被调用,并使用新的边框颜色重新绘制矩形。
要使用这个自定义的矩形项,你可以这样创建并添加到场景中:
QGraphicsScene *scene = new QGraphicsScene();
ClickableRectItem *rectItem = new ClickableRectItem(QRectF(0, 0, 100, 100));
scene->addItem(rectItem);
现在,每当你用鼠标左键点击这个矩形项时,它的边框颜色就会变为红色。如果你想要在点击后再次点击恢复原来的颜色,你可以在mousePressEvent
中添加逻辑来切换颜色。