QGraphicsSceneitem如何获取鼠标点击的item
请教大家下,我打算使用QGraphicsItem画一些点,然后鼠标点击一个点之后,可以找到是点击的哪一个点,我的做法是把所有的item存储在一个QList<QGraphicsItem *>中,然后每获取一个点,就和QLIST比较,现在的问题是无法正确的获取点击的点得item,程序一直返回最后绘制的一个点。代码如下,请教大家,1、这样做法对不对,有没有其他的办法?2、按照我的程序该如何获取鼠标点击的点得item?谢谢了!
以下是主窗口的部分代码
QList<QGraphicsItem *> itemList;
QGraphicsScene *scene;
MyItem *itemPic;//MyItem 自定义的基于QGraphicsItem的类
scene = new QGraphicsScene(this);
ui.g_grafic->setScene(scene);
for (int i = 0; i < 100; i++)
{
.........
itemPic = new MyItem(xVal, yVal);
itemList << (itemPic);
itemPic->setFlag(QGraphicsItem::ItemIsMovable);
scene->addItem(itemPic);
}
void reShootPointInfo::paintEvent(QPaintEvent *event)//希望在该函数内获得鼠标点击的Item
{
//globalPara::mouseLeftDown和globalPara::curPoint是定义的两个全局变量
update();
if (globalPara::mouseLeftDown == 1)
{
QGraphicsItem *item = itemPic->currentItem;
QList<QGraphicsItem*>item2 = scene->selectedItems();
QTransform transform;
QGraphicsItem *item9 = scene->itemAt(globalPara::curPoint.x(), globalPara::curPoint.y(), transform);
无论怎么改变坐标,这里也一直获取的是最后一个item
int index = itemList.indexOf(item);
qDebug() << "Ok!";
}
globalPara::mouseLeftDown = 0;
}
以下是基于QGraphicsItem的MyItem类
MyItem::MyItem(int x,int y)
{
this->xVal = x;
this->yVal = y;
brushColor = Qt::red;
setFlag(QGraphicsItem::ItemIsFocusable);
setFlag(QGraphicsItem::ItemIsMovable);
setFlag(QGraphicsItem::ItemIsSelectable);
}
QRectF MyItem::boundingRect() const
{
return QRectF(0,0,1000,1000);
}
void MyItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
QWidget *widget)
{
QBrush brush(Qt::red);
painter->setPen(QPen(Qt::red, 2));
painter->setBrush(brush);
painter->drawEllipse(this->xVal,this->yVal,3,3);
}
void MyItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
globalPara::mouseLeftDown = 1;
setFocus();
setCursor(Qt::ClosedHandCursor);
globalPara::curPoint = event->pos();
currentItem = QGraphicsItem::focusItem();//不管点击什么地方,这里一直获取的是最后一个item
}