我在qgraphicsScene上绘制了一个qgraphicsRectItem。通过鼠标事件,它可以在场景中移动,调整大小和位置,即选择项目mousePress和mouseMove。如何获取mouseReleaseEvent上的qgraphicsRectItem boundingRect,pos wrt场景的几何形状?
场景中有图像,并且在场景上绘制了qgraphicsRectItem的boundingrect,然后我需要获取qrect以便在边界rect中裁剪图像的该部分。
最佳答案
您必须使用以下项目的 mapRectToScene()
:
it->mapRectToScene(it->boundingRect());
例:
#include <QApplication>
#include <QGraphicsRectItem>
#include <QGraphicsSceneMouseEvent>
#include <QGraphicsView>
#include <QDebug>
class GraphicsScene: public QGraphicsScene{
public:
using QGraphicsScene::QGraphicsScene;
protected:
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event){
print_items();
QGraphicsScene::mouseReleaseEvent(event);
}
void mouseMoveEvent(QGraphicsSceneMouseEvent *event){
print_items();
QGraphicsScene::mouseMoveEvent(event);
}
private:
void print_items(){
for(QGraphicsItem *it: items()){
qDebug()<< it->data(Qt::UserRole+1).toString()<< it->mapRectToScene(it->boundingRect());
}
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QGraphicsView w;
GraphicsScene scene(0, 0, 400, 400);
w.setScene(&scene);
QGraphicsRectItem *item = new QGraphicsRectItem(QRectF(-10, -10, 20, 20));
item->setData(Qt::UserRole+1, "item1");
item->setBrush(QBrush(Qt::green));
item->setFlags(QGraphicsItem::ItemIsMovable);
QGraphicsRectItem *item2 = new QGraphicsRectItem(QRectF(0, 0, 20, 20));
item2->setData(Qt::UserRole+1, "item2");
item2->setBrush(QBrush(Qt::blue));
item2->setFlags(QGraphicsItem::ItemIsMovable);
scene.addItem(item);
scene.addItem(item2);
w.show();
return a.exec();
}