0
votes

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
        }
    }
}
  • When adding my items they start drawing from the middle of the graphics view (I set the graphics view alignment to center, which works great with addRect), also when adding more items then the graphics view screen can view the scroll bars are working, when adding my item they are disabled.
  • I’m trying to get the same behavior from the graphics view as I get when adding rect (addRect) to the scene, especially the ScrollBarAsNeeded and alignment options.

Thanks!

1
What are DeafultX, DeafultY, DeafultW, and DeafultH?Anthony
they are (0,0,100,100). I also set scroll bar to always on, in the graphicsview and it's appear but as disabled - meaning I can't use it.GoldenAxe
Try making your bounding rect function return QRectF(x, y, w, h)Anthony
Yep that did the trick, much appreciated. Can you please explain me why?GoldenAxe

1 Answers

0
votes

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.