[Interest] Draw multiple rectangles in a QGraphicsItem using the mouse
David Carmona
david.carmona93 at gmail.com
Mon Oct 19 16:39:03 CEST 2015
Hi everybody,
I would like to create a Graphical User Interface which allows the user to
draw as many rectangles as he wants on an image using the left button of
his mouse.
I have already implemented part of the code.
I have a QGraphicsView which displays an image contained in a scene :
bool ImageGraphicsView::display( QString &fileName)
{
// The image we want to display
image=new Image(fileName);
// File instanciation
file=new CreateFileAbstraction(*image);
// Save the file in the image directory
file->createFile();
rectangle=new ImageGraphicsScene(this,image);
rectangle->setSceneRect(image->rect());
item=new ImageGraphicsItem(rectangle->sceneRect(),image,file,this);
rectangle->addItem(item);
this->setScene(rectangle);
this->show();
mainWindow-> setCentralWidget(this);
mainWindow->setWindowFilePath(fileName);
return true;
}
I've added to the scene (ImageGraphicsScene) a QGraphicsItem
(ImageGraphicsItem):
QRectF ImageGraphicsItem::boundingRect()const
{
QRect p=rect.toRect();
return QRectF(p);
}
void ImageGraphicsItem::paint(QPainter *painter, const
QStyleOptionGraphicsItem *option, QWidget *widget){
if(mousePressed){
painter->drawPixmap(0,0,*pixmap);
if(selectedTool==1){
painter->drawRect(y);
painter->setPen(Qt::blue);
}
drawStarted=true;
painter->setPen(Qt::blue);
}
// The rectangle is not erased after the user unpresses the left button
else if(drawStarted) {
QPainter *tempPainter=new QPainter(pixmap);
if(selectedTool==1) {
tempPainter->drawRect(y);
tempPainter->setPen(Qt::blue);
}
painter->drawPixmap(0,0,*pixmap);
painter->setPen(Qt::blue);
tempPainter->setPen(Qt::blue);
}
painter->setPen(Qt::blue);
}
void ImageGraphicsItem::mousePressEvent(QGraphicsSceneMouseEvent *event){
mousePressed=true;
QPoint e=(event->pos()).toPoint();
if(selectedTool==1){
y.setTopLeft(e);
y.setBottomRight(e);
}
this->update();
}
void ImageGraphicsItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event){
QPoint e=(event->pos()).toPoint();
if(event->type()==QEvent::GraphicsSceneMouseMove){
if(selectedTool==1){
y.setBottomRight(e);
}
}
this->update();
}
void ImageGraphicsItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event){
mousePressed=false;
this->update();
}
With this code, i am able to draw only one rectangle and not several as I
would like.
When I actually try. Qt tells me that QPainter is not active and I can't
draw on the same QPaintDevice at the same time.
Thank you so much for your help
David
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20151019/bcd1b1e3/attachment.html>
More information about the Interest
mailing list