QGraphicsSceneitem如何获取鼠标点击的item

duanchangping 2016-06-05 06:52:09
请教大家下,我打算使用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
}
...全文
1727 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
babyzbb636 2018-12-26
  • 打赏
  • 举报
回复
您好能把代码发一下吗?非常感谢
duanchangping 2016-06-07
  • 打赏
  • 举报
回复 1
找到问题原因了,主要是boundingRect() 函数中的矩形设置范围太大了造成的,和item设置成大小一样就没有问题了
compass233 2016-06-06
  • 打赏
  • 举报
回复
update() 会触发 paintEvent 应该避免在paintEvent里用 update() repaint() Note: Generally, you should refrain from calling update() or repaint() inside a paintEvent(). For example, calling update() or repaint() on children inside a paintevent() results in undefined behavior; the child may or may not get a paint event. 你再调试看看
冷静忍耐 2016-06-06
  • 打赏
  • 举报
回复
在mousePressEvent中: currentItem = selectedItems().first(); 试一下

16,216

社区成员

发帖
与我相关
我的任务
社区描述
Qt 是一个跨平台应用程序框架。通过使用 Qt,您可以一次性开发应用程序和用户界面,然后将其部署到多个桌面和嵌入式操作系统,而无需重复编写源代码。
社区管理员
  • Qt
  • 亭台六七座
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧