我在识别自定义qgraphicsobject的id时遇到问题。我的自定义QgraphicsItem存储Id,启动X,Y位置和setFlag(QGraphicsItem :: ItemIsSelectable,true);我已将我的项目推入QMap,然后在QGraphicsScene上绘制它们。在鼠标单击期间,我可以使用items()方法获取所有项目。但是如何确定点击的项目?我可以将QGraphicsItem转换为我的类型,但我如何获得点击项目的ID?通过获取我的图形项的坐标?
我的LightObject类
public:
LightObject(qreal x, qreal y, QColor color, QGraphicsEllipseItem *parent=0);
LightObject();
void drawFocusRect(QPainter *painter);
QRectF boundingRect();
int id() const;
void setId(int id);
signals:
void setColor(const QColor&,int);
protected:
int type() const;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
virtual void setGeometry(const QRectF& rect);
virtual QSizeF sizeHint(Qt::SizeHint which,
const QSizeF& constraint = QSizeF()) const;
public slots:
private:
bool isSelected_;
int id_;
qreal xPos_;//X position on scene
qreal yPos_;
qreal radius = 60;
qreal rw_;
qreal rh_;
QColor color_;
QPixmap *mPixmap;
我的CustomScene类
void EffectPreviewScene::paintLights(int x,int y)
{
int offsetX = 10;
int offsetY = 10;
int i = 0;
for (int xcnt=0;xcnt<x;xcnt++){
for (int ycnt=0;ycnt<y;ycnt++){
QGraphicsLayoutItem *i = new QGraphicsLayoutItem(0);
LightObject *mLight = new LightObject(offsetX,offsetY,QColor( 255, 0, 0));//graphicsobject. store coordinates
mLight->setId(i);//?
mLight->setX(xcnt);
mLight->setY(ycnt);
qDebug() << "xcnt=" << xcnt;
qDebug() << "ycnt=" << ycnt;
addItem(mLight); //added
qDebug() << "offsetX=" << offsetX;
offsetY += 40;
qDebug() << "offsetY=" << offsetY;
i++;
}
}
}
void EffectPreviewScene::mousePressEvent(QGraphicsSceneMouseEvent *event)
{ //?
if(!event->isAccepted()) {
testUpdate();//repaint to green
qDebug() << "graphics scene event not accepted";
QGraphicsItem *item;
item = itemAt(event->pos(),QTransform()); //Get the item at the position //?
QList<QGraphicsItem*> potentialSelections = items();//items(event->pos());
for(auto iter = potentialSelections.begin(); iter != potentialSelections.end() ; ++iter)
{
if((*iter)->flags() & QGraphicsItem::ItemIsSelectable)
{
item = *iter;
}
}
qDebug () << "potentialSelections.size()="<<potentialSelections.size();
qDebug() << "RECT=" <<item->boundingRect();//scene becomes an item
if (item) //If there is an item at that position
{
qDebug() << "found";
qDebug() << "lights.size()"<<lights.size();
mlight = dynamic_cast<LightObject*>(item);
connect(mlight,&LightObject::setColor,mColorManager,ColorManager::colorChanged);
if (mlight){
//get x,y,id
qDebug() << "color="<< mlight->color();
qDebug() << mlight->rect();
qDebug() << "id=" << mlight->id();
}
}
}
}