在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中。
1031

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



