默认情况下,QGraphicsRectItem的坐标原点为左上角。如果需要将其设置为左下角,可以通过以下两种方式实现:
- 重写QGraphicsRectItem的boundingRect()函数,调整矩形的y轴坐标:
class MyRectItem : public QGraphicsRectItem {
public:
MyRectItem(qreal x, qreal y, qreal width, qreal height, QGraphicsItem *parent = nullptr)
: QGraphicsRectItem(x, y, width, height, parent) {}
QRectF boundingRect() const override {
return QRectF(rect().x(), -rect().y(), rect().width(), rect().height());
}
};
- 在QGraphicsView中设置坐标系原点:
QGraphicsView view;
view.setRenderHint(QPainter::Antialiasing); // 抗锯齿
view.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // 关闭垂直滚动条
view.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // 关闭水平滚动条
view.setDragMode(QGraphicsView::ScrollHandDrag); // 拖拽模式
QGraphicsScene scene;
view.setScene(&scene);
// 设置坐标系原点为左下角
scene.setSceneRect(QRectF(0, -view.height(), view.width(), view.height()));