自定义QGraphicsItem通过起点和终点画一个矩形

1. 创建自定义 QGraphicsItem

首先,定义一个继承自 QGraphicsItem 的类。这个类将重写 boundingRect()paint() 方法来绘制矩形。

#include <QGraphicsItem>
#include <QPainter>
#include <QPen>

class RectangleItem : public QGraphicsItem {
public:
    RectangleItem(QPointF topLeft, QPointF bottomRight, QGraphicsItem* parent = nullptr)
        : QGraphicsItem(parent), m_topLeft(topLeft), m_bottomRight(bottomRight) {}

    QRectF boundingRect() const override {
        // 返回一个包围矩形的矩形
        return QRectF(m_topLeft, QSizeF(m_bottomRight.x() - m_topLeft.x(), m_bottomRight.y() - m_topLeft.y()));
    }

    void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) override {
        Q_UNUSED(option);
        Q_UNUSED(widget);

        // 设置画笔颜色和宽度
        painter->setPen(QPen(Qt::black, 2));

        // 绘制矩形
        painter->drawRect(QRectF(m_topLeft, QSizeF(m_bottomRight.x() - m_topLeft.x(), m_bottomRight.y() - m_topLeft.y())));
    }

private:
    QPointF m_topLeft;
    QPointF m_bottomRight;
};

2. 使用自定义 QGraphicsItem

在你的主窗口类中,创建一个 QGraphicsScene 和一个 QGraphicsView,然后将 RectangleItem 添加到场景中。

#include <QApplication>
#include <QGraphicsScene>
#include <QGraphicsView>

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);

    QGraphicsScene scene;
    QGraphicsView view(&scene);

    // 创建一个矩形的起点为 (50, 50),终点为 (150, 100) 的 RectangleItem
    RectangleItem* rectangleItem = new RectangleItem(QPointF(50, 50), QPointF(150, 100));
    scene.addItem(rectangleItem);

    view.show();
    return app.exec();
}

3. 解释代码

  • RectangleItem 类继承自 QGraphicsItem,并重写了 boundingRect()paint() 方法。

    • boundingRect() 返回一个矩形,该矩形包含了整个绘制区域。QRectF 的构造函数使用了矩形的起点和宽高来定义这个矩形。
    • paint() 方法使用 QPainterdrawRect() 方法绘制矩形。drawRect() 方法需要一个 QRectF 参数来指定矩形的边界。
  • main() 函数创建了一个 Qt 应用程序,设置了一个场景和视图,并将自定义的 RectangleItem 添加到场景中。

注意事项

  • boundingRect() 方法返回的矩形应该足够大,以包含整个绘制的矩形,这对性能优化和正确的重绘非常重要。
  • 矩形的起点和终点可以根据需要调整,RectangleItem 的构造函数允许你指定这些值。

通过上述步骤,你可以自定义一个 QGraphicsItem 来在 Qt 的图形视图框架中绘制矩形。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值