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()
方法使用QPainter
的drawRect()
方法绘制矩形。drawRect()
方法需要一个QRectF
参数来指定矩形的边界。
-
main()
函数创建了一个 Qt 应用程序,设置了一个场景和视图,并将自定义的RectangleItem
添加到场景中。
注意事项
boundingRect()
方法返回的矩形应该足够大,以包含整个绘制的矩形,这对性能优化和正确的重绘非常重要。- 矩形的起点和终点可以根据需要调整,
RectangleItem
的构造函数允许你指定这些值。
通过上述步骤,你可以自定义一个 QGraphicsItem
来在 Qt 的图形视图框架中绘制矩形。