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!
QRectF(x, y, w, h)
– Anthony