自定义项目 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);
}
添加到场景:
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
}
}
}
- 添加我的项目时,他们从图形视图的中间开始绘制(我将图形视图对齐设置为居中,这与 addRect 配合得很好),当添加更多项目时,图形视图屏幕可以查看滚动条正在工作,当添加我的项目他们被禁用。
- 我试图从图形视图中获得与在场景中添加 rect (addRect) 时相同的行为,尤其是 ScrollBarAsNeeded 和对齐选项。
谢谢!