C++ (Qt)void QGraphicsItem::setData(int key, const QVariant & value)
#define KEY_I Qt::UserRole+1#define KEY_J Qt::UserRole+2
item->setData(KEY_I, i);item->setData(KEY_J, j);
int i,j;i = item->data(KEY_I).toInt();j = item->data(KEY_J).toInt();
//////////////////////// myitem.h ////////////////////////////////#ifndef MYITEM_H#define MYITEM_H#include <QPainter>#include <QGraphicsItem>#include <QDebug>#include <QMessageBox>class MyItem : public QGraphicsItem{public: int i,j; MyItem(); QRectF boundingRect() const; void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); void setData(int key, const QVariant &value) { i=value.toInt(); } ~MyItem();protected: void mousePressEvent(QGraphicsSceneMouseEvent *event);private: QMessageBox *qb;};#endif // MYITEM_H//////////////////////// myitem.cpp ////////////////////////MyItem::MyItem(){}void MyItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget){ QRectF rec = boundingRect(); QBrush brush(Qt::blue); painter->fillRect(rec,brush); painter->drawRect(rec);}void MyItem::mousePressEvent(QGraphicsSceneMouseEvent *event){ QGraphicsItem::mousePressEvent(event); qb = new QMessageBox(); // qb->setText(QString::number(ik)+" "+QString::number(jk)); qb->show();}MyItem::~MyItem(){}//////////////////////// dialog.cpp //////////////////////////#include "dialog.h"#include "ui_dialog.h"#define KEY_I Qt::UserRole+1#define KEY_J Qt::UserRole+2 int i1,j1;Dialog::Dialog(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog){ ui->setupUi(this); scene = new QGraphicsScene(this); ui->graphicsView->setScene(scene); square = new MyItem(); for (j1=0; j1<10; j1++) for (i1=0; i1<10; i1++) { square->setData(KEY_I, i1); square->setData(KEY_J, j1); scene->addItem(square);}}Dialog::~Dialog(){ delete ui;}QRectF MyItem::boundingRect() const{ return QRectF(i1*5,j1*5,3,3);}