自定义项目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
}
}
}
谢谢!
答案 0 :(得分:0)
你的边界矩形不太正确。假设您的项目是矩形,您的边界矩形应该与您在绘制事件中绘制的矩形相同。因此,在您的绘画活动中,您应该可以致电painter->drawRect(boundingRect());
请注意,您正在做的另一种方法是使用QGraphicsItem的位置(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);
}
}
我认为这有点清洁,但这取决于你。