qt 6.7,用QGraphicsRectItem画一个矩形,且要求矩形的两边有一个红色的小矩形,小矩形的中心,是两个边线的中心点。这三个图形要求画在一个QGraphicsRectItem对象中

在Qt 6.7中,如果你想要在一个QGraphicsRectItem对象中绘制一个主矩形以及两个位于其两侧中心点的红色小矩形,你不能直接在一个QGraphicsRectItem中绘制多个形状,因为QGraphicsRectItem只表示一个简单的矩形。不过,你可以通过创建一个自定义的QGraphicsItem类来实现这个需求。

以下是一个自定义QGraphicsItem的示例,该类将绘制一个主矩形和两个位于其两侧中心点的红色小矩形:

#include <QGraphicsItem>  
#include <QPainter>  
#include <QRectF>  
  
class CustomRectItem : public QGraphicsItem {  
public:  
    CustomRectItem(QGraphicsItem *parent = nullptr) : QGraphicsItem(parent) {  
        // 设置主矩形的尺寸  
        mainRect = QRectF(0, 0, 200, 100);  
        // 设置小矩形的尺寸  
        smallRect = QRectF(0, 0, 10, 10);  
    }  
  
    QRectF boundingRect() const override {  
        // 返回包含所有图形的边界矩形  
        return mainRect.adjusted(-smallRect.width()/2, -smallRect.height()/2,  
                                 smallRect.width()/2, smallRect.height()/2);  
    }  
  
    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override {  
        Q_UNUSED(option)  
        Q_UNUSED(widget)  
  
        // 绘制主矩形  
        painter->setPen(QPen(Qt::black));  
        painter->setBrush(Qt::white);  
        painter->drawRect(mainRect);  
  
        // 绘制左侧的小矩形  
        QPointF leftCenter = QPointF(mainRect.left() - smallRect.width()/2, mainRect.center().y());  
        painter->setPen(QPen(Qt::red));  
        painter->setBrush(Qt::red);  
        painter->drawRect(QRectF(leftCenter, smallRect.size()));  
  
        // 绘制右侧的小矩形  
        QPointF rightCenter = QPointF(mainRect.right() + smallRect.width()/2, mainRect.center().y());  
        painter->drawRect(QRectF(rightCenter, smallRect.size()));  
    }  
  
private:  
    QRectF mainRect;  // 主矩形的尺寸和位置  
    QRectF smallRect; // 小矩形的尺寸  
};

在这个类中,我们重写了boundingRect()paint()方法。boundingRect()返回包含主矩形和两个小矩形的最小矩形。paint()方法负责绘制主矩形和两个位于其两侧中心点的小矩形。

现在,你可以在Qt应用程序中使用CustomRectItem类来创建和显示这个组合图形:

#include <QApplication>  
#include <QGraphicsScene>  
#include <QGraphicsView>  
#include "CustomRectItem.h" // 确保包含自定义类的头文件  
  
int main(int argc, char *argv[]) {  
    QApplication app(argc, argv);  
  
    QGraphicsScene scene;  
    CustomRectItem *item = new CustomRectItem();  
    scene.addItem(item);  
  
    QGraphicsView view(&scene);  
    view.show();  
  
    return app.exec();  
}

这段代码创建了一个QGraphicsScene,向其中添加了一个CustomRectItem实例,并显示在一个QGraphicsView中。

 

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值