在Qt框架中,QGraphicsScene
类用于管理和渲染2D图形项。要获取 QGraphicsScene
中的坐标,您通常是指获取某个图形项(如 QGraphicsItem
)在场景中的位置,或者获取鼠标点击事件在场景中的坐标。
获取图形项在场景中的坐标
如果您有一个 QGraphicsItem
对象,并且想要获取它在 QGraphicsScene
中的位置,可以使用 pos()
方法。例如:
QGraphicsItem* item = ...; // 您的 QGraphicsItem 对象
QPointF itemPosition = item->pos();
qDebug() << "Item position:" << itemPosition;
获取鼠标点击事件在场景中的坐标
如果您想要处理鼠标点击事件并获取点击位置在 QGraphicsScene
中的坐标,可以重载 QGraphicsScene
的 mousePressEvent
方法。例如:
class MyScene : public QGraphicsScene {
protected:
void mousePressEvent(QGraphicsSceneMouseEvent* event) override {
QPointF scenePos = event->scenePos();
qDebug() << "Mouse click position in scene:" << scenePos;
QGraphicsScene::mousePressEvent(event); // 调用基类方法以确保默认行为
}
};
示例程序
以下是一个简单的示例程序,展示了如何创建一个自定义的 QGraphicsScene
并处理鼠标点击事件以获取点击位置:
#include <QApplication>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsEllipseItem>
#include <QDebug>
class MyScene : public QGraphicsScene {
protected:
void mousePressEvent(QGraphicsSceneMouseEvent* event) override {
QPointF scenePos = event->scenePos();
qDebug() << "Mouse click position in scene:" << scenePos;
// 可选:在点击位置添加一个椭圆项作为标记
QGraphicsEllipseItem* ellipse = new QGraphicsEllipseItem(scenePos.x() - 5, scenePos.y() - 5, 10, 10);
this->addItem(ellipse);
QGraphicsScene::mousePressEvent(event); // 调用基类方法
}
};
int main(int argc, char** argv) {
QApplication app(argc, argv);
MyScene scene;
QGraphicsView view(&scene);
// 添加一个矩形项作为参考
scene.addRect(0, 0, 200, 200, QPen(Qt::black), QBrush(Qt::green));
view.setSceneRect(0, 0, 400, 400);
view.show();
return app.exec();
}
在这个示例程序中,当您点击场景时,程序会在控制台中输出点击位置,并在点击位置添加一个小的椭圆作为标记。
希望这些信息对您有所帮助!如果您有更多问题,请随时提问。