Custom item cpp:
MapNode::MapNode(qreal x, qreal y, qreal w, qreal h, QGraphicsItem *parent)
{
this->x = x;
this->y = y;
this->w = w;
this->h = h;
}
QRectF MapNode::boundingRect() const
{
return QRectF(DeafultX, DeafultY, DeafultW, DeafultH);
}
void MapNode::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
QBrush redBrush(Qt::red);
QPen blackPen(Qt::black);
blackPen.setWidth(1);
painter->setBrush(redBrush);
painter->setPen(blackPen);
painter->drawRect(x,y,w,h);
}
Add to Scene:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
scene = new QGraphicsScene(this);
ui->graphicsView->setScene(scene);
QBrush redBrush(Qt::red);
QPen blackPen(Qt::black);
blackPen.setWidth(1);
for(int i = 0; i < 992; i+=62)
{
for(int j = 0; j < 992; j+=62)
{
QGraphicsItem *myItem = new MapNode(i,j,60,60);
scene->addItem(myItem);
//scene->addRect(i,j,60,60,blackPen,redBrush); //working fine
}
}
}
Thanks!
Your bounding rect isn't quite right. Assuming your item is rectangular in shape, your bounding rect should be the same as the rect you draw in your paint event. So in your paint event, you should be able to call painter->drawRect(boundingRect());
Note that an alternative approach to what you're doing is to make use of a QGraphicsItem's position (QGraphicsItem::setPos()
):
for(int i = 0; i < 992; i+=62)
{
for(int j = 0; j < 992; j+=62)
{
QGraphicsItem *myItem = new MapNode(0, 0, 60, 60);
myItem->setPos(i, j);
scene->addItem(myItem);
}
}
I think this is a bit cleaner, but it's up to you.