1.需求
qt 6.7,用QGraphicsRectItem画一个矩形,且要求矩形的两边有一个红色的小矩形,小矩形的中心,是两个边线的中心点。这三个图形要求画在一个QGraphicsRectItem对象中
这个需求的主要意图是想创建一个可以拖拽、缩放的矩形,左右图拽的时候,点击两侧的小矩形就可以拖拽矩形
2.代码
1.矩形绘制函数
#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()-smallRect.width()/2);
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()-smallRect.width()/2);
painter->drawRect(QRectF(rightCenter, smallRect.size()));
}
private:
QRectF mainRect; // 主矩形的尺寸和位置
QRectF smallRect; // 小矩形的尺寸
};
2.主函数
#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();
}