在Qt中,QGraphicsRectItem本身并不直接提供设置边框颜色的功能。但是,你可以通过继承QGraphicsRectItem或QGraphicsItem并重写其paint()方法来自定义矩形的绘制,包括边框颜色。
下面是一个简单的示例,展示了如何通过继承QGraphicsRectItem来设置矩形边框颜色:
#include <QGraphicsRectItem>
#include <QPainter>
class ColoredRectItem : public QGraphicsRectItem {
public:
ColoredRectItem(const QRectF &rect, QGraphicsItem *parent = nullptr)
: QGraphicsRectItem(rect, parent) {
// 设置边框颜色
borderColor = Qt::red;
}
void setBorderColor(const QColor &color) {
borderColor = color;
update(); // 更新项以重绘
}
protected:
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) override {
QPen pen(borderColor);
pen.setWidth(2); // 设置边框宽度
painter->setPen(pen);
painter->setBrush(Qt::NoBrush); // 不填充矩形内部
painter->drawRect(rect()); // 绘制矩形边框
}
private:
QColor borderColor;
};
在这个示例中,ColoredRectItem类继承自QGraphicsRectItem。它有一个borderColor成员变量来存储边框颜色,并且提供了一个setBorderColor方法来设置这个颜色。在paint方法中,使用QPainter来绘制矩形边框,并设置笔的颜色和宽度。注意,rect()方法返回的是矩形的位置和大小,它在QGraphicsRectItem中定义。
要使用这个自定义的矩形项,你可以这样创建和添加到场景中:
QGraphicsScene *scene = new QGraphicsScene();
ColoredRectItem *rectItem = new ColoredRectItem(QRectF(0, 0, 100, 100));
scene->addItem(rectItem);
rectItem->setBorderColor(Qt::blue); // 设置边框颜色为蓝色
1324

被折叠的 条评论
为什么被折叠?



