Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. How to draw on Image loaded in a QGraphicsView
Forum Updated to NodeBB v4.3 + New Features

How to draw on Image loaded in a QGraphicsView

Scheduled Pinned Locked Moved Solved General and Desktop
drawqgraphicsviewc++c++ qtclass
22 Posts 4 Posters 17.1k Views 4 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • SGaistS Offline
    SGaistS Offline
    SGaist
    Lifetime Qt Champion
    wrote on last edited by
    #2

    Hi and welcome to devnet,

    What do you want to draw on that image ?

    Interested in AI ? www.idiap.ch
    Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

    1 Reply Last reply
    0
    • N Nico1564

      Hello everyone, I have a problem.

      I have created a mainWindow with some Widgets in Layouts and one of this widget is a QGraphicsView in which I loaded an image.
      In fact, it was not really me, because i used the following class find in this link : https://www.lucidarme.me/scroll-zoom-drag-tooltip-contextual-menu-and-draw-in-an-image-widget/

      This class let me zoom in and out the picture and move it.

      My problem is that, even after a lot of hours, i can't draw anything over the picture.

      Can someone help me ?

      NB : I could not show my entire code because there are more than 1000 lines

      K Offline
      K Offline
      kenchan
      wrote on last edited by
      #3

      @Nico1564
      It depends on what you want to draw on top. If you drew the image in a QGraphicsBitmapItem and you want to draw primitives like lines or text etc. on top, just draw them in the correct position after you draw the bitmap. The draw order will take car of it.
      Or, make the bitmap item the parent of the items you want to draw on top i.e. children are draw after parents unless you change that behaviour.
      You should really show people the code you use to draw the bitmap, don't need your whole code base :-)

      1 Reply Last reply
      1
      • N Offline
        N Offline
        Nico1564
        wrote on last edited by
        #4

        Hi SGaist and kenchan, thank you for answer

        I want (first) draw some basic things like a circle and a line. Next i want to "draw" an other image more smaller than the first one and it have to move on the first picture.

        Here is the code of the class :

        #rOg_image.cpp
        #include "rOg_image.h"

        // Constructor of the class, create the scene and set default parameters
        rOg_image::rOg_image(bool isContextualMenu, QWidget * parent) :
        QGraphicsView(parent)
        {
        // Set default zoom factors
        zoomFactor=DEFAULT_ZOOM_FACTOR;
        zoomCtrlFactor=DEFAULT_ZOOM_CTRL_FACTOR;

        // Create the scene
        scene = new QGraphicsScene();
        
        // Allow mouse tracking even if no button is pressed
        this->setMouseTracking(true);
        
        // Add the scene to the QGraphicsView
        this->setScene(scene);
        
        // Update all the view port when needed, otherwise, the drawInViewPort may experience trouble
        this->setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
        
        // When zooming, the view stay centered over the mouse
        this->setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
        
        this->setResizeAnchor(QGraphicsView::AnchorViewCenter);
        
        // Initialize contextual menu if requested
        if (isContextualMenu)
        {
            setContextMenuPolicy(Qt::CustomContextMenu);
            connect(this, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showContextMenu(const QPoint&)));
        }
        
        // Disable scroll bar to avoid a unwanted resize recursion
        

        // setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
        // setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

        // Add the default pixmap at startup
        pixmapItem = scene->addPixmap(pixmap);
        

        }

        // Destructor of the class
        rOg_image::~rOg_image()
        {
        delete pixmapItem;
        delete scene;
        }

        // Display contextual menu
        void rOg_image::showContextMenu(const QPoint & pos)
        {
        // Get the mouse position in the scene
        QPoint globalPos = mapToGlobal(pos);
        // Create the menu and add action
        QMenu contextMenu;
        contextMenu.addAction("Reset view", this, SLOT(fitImage()));
        // Display the menu
        contextMenu.exec(globalPos);
        }

        // Set or update the image in the scene
        void rOg_image::setImage(const QImage & image)
        {
        // Update the pixmap in the scene
        pixmap=QPixmap::fromImage(image);
        pixmapItem->setPixmap(pixmap);

        // Resize the scene (needed is the new image is smaller)
        scene->setSceneRect(QRect (QPoint(0,0),image.size()));
        
        // Store the image size
        imageSize = image.size();
        

        }

        // Set an image from raw data
        void rOg_image::setImageFromRawData(const uchar * data, int width, int height, bool mirrorHorizontally, bool mirrorVertically)
        {
        // Convert data into QImage
        QImage image(data, width, height, width*3, QImage::Format_RGB888);

        // Update the pixmap in the scene
        pixmap=QPixmap::fromImage(image.mirrored(mirrorHorizontally,mirrorVertically));
        pixmapItem->setPixmap(pixmap);
        
        // Resize the scene (needed is the new image is smaller)
        scene->setSceneRect(QRect (QPoint(0,0),image.size()));
        
        // Store the image size
        imageSize = image.size();
        

        }

        // Fit the image in the widget
        void rOg_image::fitImage()
        {
        // Get current scroll bar policy
        Qt::ScrollBarPolicy currentHorizontalPolicy = horizontalScrollBarPolicy();
        Qt::ScrollBarPolicy currentverticalPolicy = verticalScrollBarPolicy();

        // Disable scroll bar to avoid a margin around the image
        setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
        setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
        
        // Fit the scene in the QGraphicsView
        this->fitInView(scene->sceneRect(), Qt::KeepAspectRatio);
        
        // Restaure scroll bar policy
        setHorizontalScrollBarPolicy(currentHorizontalPolicy);
        setVerticalScrollBarPolicy(currentverticalPolicy);
        

        }

        // Called when a mouse button is pressed
        void rOg_image::mousePressEvent(QMouseEvent *event)
        {
        // Drag mode : change the cursor's shape
        if (event->button() == Qt::LeftButton) this->setDragMode(QGraphicsView::ScrollHandDrag);
        // if (event->button() == Qt::RightButton) this->fitImage();
        QGraphicsView::mousePressEvent(event);
        }

        // Called when a mouse button is pressed
        void rOg_image::mouseReleaseEvent(QMouseEvent *event)
        {
        // Exit drag mode : change the cursor's shape
        if (event->button() == Qt::LeftButton) this->setDragMode(QGraphicsView::NoDrag);
        QGraphicsView::mouseReleaseEvent(event);
        }

        #ifndef QT_NO_WHEELEVENT

        // Call when there is a scroll event (zoom in or zoom out)
        void rOg_image::wheelEvent(QWheelEvent *event)
        {
        // When zooming, the view stay centered over the mouse
        this->setTransformationAnchor(QGraphicsView::AnchorUnderMouse);

        double factor = (event->modifiers() & Qt::ControlModifier) ? zoomCtrlFactor : zoomFactor;
        if(event->delta() > 0)
            // Zoom in
            scale(factor, factor);
        else
            // Zooming out
            scale(1.0 / factor, 1.0 / factor);
        
        // The event is processed
        event->accept();
        

        }

        #endif

        // Overload the mouse MoveEvent to display the tool tip
        void rOg_image::mouseMoveEvent(QMouseEvent *event)
        {
        // Get the coordinates of the mouse in the scene
        QPointF imagePoint = mapToScene(QPoint(event->x(), event->y() ));
        // Call the function that create the tool tip
        setToolTip(setToolTipText(QPoint((int)imagePoint.x(),(int)imagePoint.y())));
        // Call the parent's function (for dragging)
        QGraphicsView::mouseMoveEvent(event);
        }

        // Overload the function to draw over the image
        void rOg_image::drawForeground(QPainter *painter, const QRectF&)
        {

        // Call the function to draw over the image
        this->drawOnImage(painter,imageSize);
        
        // Reset transformation and call the function draw in the view port
        painter->resetTransform();
        
        // Call the function to draw in the view port
        this->drawInViewPort(painter, this->viewport()->size());
        

        }

        // Overloaded functionthat catch the resize event
        void rOg_image::resizeEvent(QResizeEvent *event)
        {
        // First call, the scene is created
        if(event->oldSize().width() == -1 || event->oldSize().height() == -1) return;

        // Get the previous rectangle of the scene in the viewport
        QPointF P1=mapToScene(QPoint(0,0));
        QPointF P2=mapToScene(QPoint(event->oldSize().width(),event->oldSize().height()));
        
        // Stretch the rectangle around the scene
        if (P1.x()<0) P1.setX(0);
        if (P1.y()<0) P1.setY(0);
        if (P2.x()>scene->width()) P2.setX(scene->width());
        if (P2.y()>scene->height()) P2.setY(scene->height());
        
        // Fit the previous area in the scene
        this->fitInView(QRect(P1.toPoint(),P2.toPoint()),Qt::KeepAspectRatio);
        

        }

        // Define the virtual function to avoid the "unused parameter" warning
        QString rOg_image::setToolTipText(QPoint imageCoordinates)
        {
        (void)imageCoordinates;
        return QString("");
        }

        // Define the virtual function to avoid the "unused parameter" warning
        void rOg_image::drawOnImage(QPainter* , QSize )
        {}

        // Define the virtual function to avoid the "unused parameter" warning
        void rOg_image::drawInViewPort(QPainter* , QSize )
        {}

        in my mainwindow (called QtGuiApplication1.cpp) i create an instance with the next lines :

        imgWidget = new rOg_image(this);

        #ifdef LOAD_RAW_RGB_DATA

        // Prepare raw image data, format is RGBRGBRGB...
        data = new uchar[WIDTH*HEIGHT * 3];
        int index = 0;
        for (int y = 0;y<HEIGHT;y++)
        	for (int x = 0;x<WIDTH;x++)
        	{
        		data[index++] = 0xFF * (x<(2.*WIDTH / 3.)); // || 0x00;
        		data[index++] = 0xFF * (x>(WIDTH / 3.) && (x<(2 * WIDTH / 3.)));
        		data[index++] = 0xFF * (x>(WIDTH / 3.));
        	}
        // Draw the raw image in the image widget
        imgWidget->setImageFromRawData(data, WIDTH, HEIGHT);
        

        #endif

        // Set background color (gray)
        imgWidget->setBackgroundBrush(QBrush(QColor(0x7F, 0x7F, 0x7F)));
        
        K 1 Reply Last reply
        0
        • N Nico1564

          Hi SGaist and kenchan, thank you for answer

          I want (first) draw some basic things like a circle and a line. Next i want to "draw" an other image more smaller than the first one and it have to move on the first picture.

          Here is the code of the class :

          #rOg_image.cpp
          #include "rOg_image.h"

          // Constructor of the class, create the scene and set default parameters
          rOg_image::rOg_image(bool isContextualMenu, QWidget * parent) :
          QGraphicsView(parent)
          {
          // Set default zoom factors
          zoomFactor=DEFAULT_ZOOM_FACTOR;
          zoomCtrlFactor=DEFAULT_ZOOM_CTRL_FACTOR;

          // Create the scene
          scene = new QGraphicsScene();
          
          // Allow mouse tracking even if no button is pressed
          this->setMouseTracking(true);
          
          // Add the scene to the QGraphicsView
          this->setScene(scene);
          
          // Update all the view port when needed, otherwise, the drawInViewPort may experience trouble
          this->setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
          
          // When zooming, the view stay centered over the mouse
          this->setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
          
          this->setResizeAnchor(QGraphicsView::AnchorViewCenter);
          
          // Initialize contextual menu if requested
          if (isContextualMenu)
          {
              setContextMenuPolicy(Qt::CustomContextMenu);
              connect(this, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showContextMenu(const QPoint&)));
          }
          
          // Disable scroll bar to avoid a unwanted resize recursion
          

          // setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
          // setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

          // Add the default pixmap at startup
          pixmapItem = scene->addPixmap(pixmap);
          

          }

          // Destructor of the class
          rOg_image::~rOg_image()
          {
          delete pixmapItem;
          delete scene;
          }

          // Display contextual menu
          void rOg_image::showContextMenu(const QPoint & pos)
          {
          // Get the mouse position in the scene
          QPoint globalPos = mapToGlobal(pos);
          // Create the menu and add action
          QMenu contextMenu;
          contextMenu.addAction("Reset view", this, SLOT(fitImage()));
          // Display the menu
          contextMenu.exec(globalPos);
          }

          // Set or update the image in the scene
          void rOg_image::setImage(const QImage & image)
          {
          // Update the pixmap in the scene
          pixmap=QPixmap::fromImage(image);
          pixmapItem->setPixmap(pixmap);

          // Resize the scene (needed is the new image is smaller)
          scene->setSceneRect(QRect (QPoint(0,0),image.size()));
          
          // Store the image size
          imageSize = image.size();
          

          }

          // Set an image from raw data
          void rOg_image::setImageFromRawData(const uchar * data, int width, int height, bool mirrorHorizontally, bool mirrorVertically)
          {
          // Convert data into QImage
          QImage image(data, width, height, width*3, QImage::Format_RGB888);

          // Update the pixmap in the scene
          pixmap=QPixmap::fromImage(image.mirrored(mirrorHorizontally,mirrorVertically));
          pixmapItem->setPixmap(pixmap);
          
          // Resize the scene (needed is the new image is smaller)
          scene->setSceneRect(QRect (QPoint(0,0),image.size()));
          
          // Store the image size
          imageSize = image.size();
          

          }

          // Fit the image in the widget
          void rOg_image::fitImage()
          {
          // Get current scroll bar policy
          Qt::ScrollBarPolicy currentHorizontalPolicy = horizontalScrollBarPolicy();
          Qt::ScrollBarPolicy currentverticalPolicy = verticalScrollBarPolicy();

          // Disable scroll bar to avoid a margin around the image
          setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
          setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
          
          // Fit the scene in the QGraphicsView
          this->fitInView(scene->sceneRect(), Qt::KeepAspectRatio);
          
          // Restaure scroll bar policy
          setHorizontalScrollBarPolicy(currentHorizontalPolicy);
          setVerticalScrollBarPolicy(currentverticalPolicy);
          

          }

          // Called when a mouse button is pressed
          void rOg_image::mousePressEvent(QMouseEvent *event)
          {
          // Drag mode : change the cursor's shape
          if (event->button() == Qt::LeftButton) this->setDragMode(QGraphicsView::ScrollHandDrag);
          // if (event->button() == Qt::RightButton) this->fitImage();
          QGraphicsView::mousePressEvent(event);
          }

          // Called when a mouse button is pressed
          void rOg_image::mouseReleaseEvent(QMouseEvent *event)
          {
          // Exit drag mode : change the cursor's shape
          if (event->button() == Qt::LeftButton) this->setDragMode(QGraphicsView::NoDrag);
          QGraphicsView::mouseReleaseEvent(event);
          }

          #ifndef QT_NO_WHEELEVENT

          // Call when there is a scroll event (zoom in or zoom out)
          void rOg_image::wheelEvent(QWheelEvent *event)
          {
          // When zooming, the view stay centered over the mouse
          this->setTransformationAnchor(QGraphicsView::AnchorUnderMouse);

          double factor = (event->modifiers() & Qt::ControlModifier) ? zoomCtrlFactor : zoomFactor;
          if(event->delta() > 0)
              // Zoom in
              scale(factor, factor);
          else
              // Zooming out
              scale(1.0 / factor, 1.0 / factor);
          
          // The event is processed
          event->accept();
          

          }

          #endif

          // Overload the mouse MoveEvent to display the tool tip
          void rOg_image::mouseMoveEvent(QMouseEvent *event)
          {
          // Get the coordinates of the mouse in the scene
          QPointF imagePoint = mapToScene(QPoint(event->x(), event->y() ));
          // Call the function that create the tool tip
          setToolTip(setToolTipText(QPoint((int)imagePoint.x(),(int)imagePoint.y())));
          // Call the parent's function (for dragging)
          QGraphicsView::mouseMoveEvent(event);
          }

          // Overload the function to draw over the image
          void rOg_image::drawForeground(QPainter *painter, const QRectF&)
          {

          // Call the function to draw over the image
          this->drawOnImage(painter,imageSize);
          
          // Reset transformation and call the function draw in the view port
          painter->resetTransform();
          
          // Call the function to draw in the view port
          this->drawInViewPort(painter, this->viewport()->size());
          

          }

          // Overloaded functionthat catch the resize event
          void rOg_image::resizeEvent(QResizeEvent *event)
          {
          // First call, the scene is created
          if(event->oldSize().width() == -1 || event->oldSize().height() == -1) return;

          // Get the previous rectangle of the scene in the viewport
          QPointF P1=mapToScene(QPoint(0,0));
          QPointF P2=mapToScene(QPoint(event->oldSize().width(),event->oldSize().height()));
          
          // Stretch the rectangle around the scene
          if (P1.x()<0) P1.setX(0);
          if (P1.y()<0) P1.setY(0);
          if (P2.x()>scene->width()) P2.setX(scene->width());
          if (P2.y()>scene->height()) P2.setY(scene->height());
          
          // Fit the previous area in the scene
          this->fitInView(QRect(P1.toPoint(),P2.toPoint()),Qt::KeepAspectRatio);
          

          }

          // Define the virtual function to avoid the "unused parameter" warning
          QString rOg_image::setToolTipText(QPoint imageCoordinates)
          {
          (void)imageCoordinates;
          return QString("");
          }

          // Define the virtual function to avoid the "unused parameter" warning
          void rOg_image::drawOnImage(QPainter* , QSize )
          {}

          // Define the virtual function to avoid the "unused parameter" warning
          void rOg_image::drawInViewPort(QPainter* , QSize )
          {}

          in my mainwindow (called QtGuiApplication1.cpp) i create an instance with the next lines :

          imgWidget = new rOg_image(this);

          #ifdef LOAD_RAW_RGB_DATA

          // Prepare raw image data, format is RGBRGBRGB...
          data = new uchar[WIDTH*HEIGHT * 3];
          int index = 0;
          for (int y = 0;y<HEIGHT;y++)
          	for (int x = 0;x<WIDTH;x++)
          	{
          		data[index++] = 0xFF * (x<(2.*WIDTH / 3.)); // || 0x00;
          		data[index++] = 0xFF * (x>(WIDTH / 3.) && (x<(2 * WIDTH / 3.)));
          		data[index++] = 0xFF * (x>(WIDTH / 3.));
          	}
          // Draw the raw image in the image widget
          imgWidget->setImageFromRawData(data, WIDTH, HEIGHT);
          

          #endif

          // Set background color (gray)
          imgWidget->setBackgroundBrush(QBrush(QColor(0x7F, 0x7F, 0x7F)));
          
          K Offline
          K Offline
          kenchan
          wrote on last edited by kenchan
          #5

          @Nico1564
          OK, so what I understand from your code is, you are adding an image to the scene in the constructor of your QGraphicsView. Then, you add another image to the scene later, correct?
          BTW, when you add the second image you do not remove the old one but you overwrite the pointer to the first pixmap item in your class, is this deliberate?

          So, the problem is what, you can't see the second image only the first one?
          I don't see why you have to over load the drawForeground() function but I guess that came with the code you downloaded?
          So your first image is a kind of background for your later drawing?

          1 Reply Last reply
          0
          • N Offline
            N Offline
            Nico1564
            wrote on last edited by Nico1564
            #6

            @kenchan this code is only the code that I have download. And yes in fact, there is 2 images, 1 is a grey background (set by the foncion setImageFromRawData) and the second is and image that i choose with this code in the QtGuiApplication1.cpp :

                    QString fichier = QFileDialog::getOpenFileName(this, "Ouvrir un fichier", QString(), "Images (*.png *.gif *.jpg *.jpeg)");
            	if (fichier.isEmpty())
            	{
            		QMessageBox::critical(this, "Erreur", "Erreur dans la selection de l'image");
            	}
            	else
            	{
            		QMessageBox::information(this, "Fichier", "Vous avez selectionne :\n" + fichier);
            		imgWidget->setImage(QImage(fichier));
            		ui.horizontalLayout->addWidget(imgWidget);
            

            ui.horizontalLayout is a Layout in my MainWindow

            Do you think that I can put my "draws" converted in QImages with the same type of lines ?

            K 1 Reply Last reply
            0
            • N Nico1564

              @kenchan this code is only the code that I have download. And yes in fact, there is 2 images, 1 is a grey background (set by the foncion setImageFromRawData) and the second is and image that i choose with this code in the QtGuiApplication1.cpp :

                      QString fichier = QFileDialog::getOpenFileName(this, "Ouvrir un fichier", QString(), "Images (*.png *.gif *.jpg *.jpeg)");
              	if (fichier.isEmpty())
              	{
              		QMessageBox::critical(this, "Erreur", "Erreur dans la selection de l'image");
              	}
              	else
              	{
              		QMessageBox::information(this, "Fichier", "Vous avez selectionne :\n" + fichier);
              		imgWidget->setImage(QImage(fichier));
              		ui.horizontalLayout->addWidget(imgWidget);
              

              ui.horizontalLayout is a Layout in my MainWindow

              Do you think that I can put my "draws" converted in QImages with the same type of lines ?

              K Offline
              K Offline
              kenchan
              wrote on last edited by kenchan
              #7

              @Nico1564
              I don't understand what you mean by this:
              "Do you think that I can put my "draws" converted in QImages with the same type of lines ?"
              You should be able to just draw on top of previously dawn items. That is the natural draw order for a QGraphicsScene. I can't see why it will not do this for you. I must look more closely at your code.
              Can you post a screen shot of how it appears now?

              1 Reply Last reply
              0
              • N Offline
                N Offline
                Nico1564
                wrote on last edited by
                #8

                in fact i just begin the c++ programming, and i'm a little lost. I know how to draw but in this case, i don't know where because i don't want to draw in the scene but on the (real) Image (not the background)

                What i wanted to say is that, if i recall SetImage(....) in my QtGuiApplication1, does the previous picture will be replaced by the new one or not ?

                I could not upload all my code for confidentials reason, so let me some times to hide somes lines pls

                K 1 Reply Last reply
                0
                • N Nico1564

                  in fact i just begin the c++ programming, and i'm a little lost. I know how to draw but in this case, i don't know where because i don't want to draw in the scene but on the (real) Image (not the background)

                  What i wanted to say is that, if i recall SetImage(....) in my QtGuiApplication1, does the previous picture will be replaced by the new one or not ?

                  I could not upload all my code for confidentials reason, so let me some times to hide somes lines pls

                  K Offline
                  K Offline
                  kenchan
                  wrote on last edited by kenchan
                  #9

                  @Nico1564
                  Ah, you say you don't want to draw in the scene but draw something on the actual image and then put that in the scene?
                  OK, you could make a painter draw on the image then draw other things on the image using the painter. Then you could draw the resulting image in the scene, if that is what you mean.
                  have a function to draw on the image something like this, then put the image in the scene.

                      QImage image(512,512,QImage::Format_RGBA8888);
                      image.fill(QColor(128,128,128));
                      QPainter painter(&image);
                      //...
                      //draw something on the image
                      painter.drawRect(200,200,200,200);
                      //...
                      painter.end();
                  
                  1 Reply Last reply
                  1
                  • N Offline
                    N Offline
                    Nico1564
                    wrote on last edited by
                    #10

                    Ok so to do that, i should modify this part of the QtGuiApplication.cpp ?

                    	QString fichier = QFileDialog::getOpenFileName(this, "Ouvrir un fichier", QString(), "Images (*.png *.gif *.jpg *.jpeg)");
                    	if (fichier.isEmpty())
                    	{
                    		QMessageBox::critical(this, "Erreur", "Erreur dans la selection de l'image");
                    	}
                    	else
                    	{
                    		QMessageBox::information(this, "Fichier", "Vous avez selectionne :\n" + fichier);
                    		//create painter with fichier then draw my circle on this painter
                    		imgWidget->setImage(QImage(fichier));
                    		ui.horizontalLayout->addWidget(imgWidget);
                    		defCoos();
                    	}
                    

                    Another question on my circle, once I have drawn it, I could not delete it right ? Or there is a system of layer with QPainter or QImage like we should find in Photoshop for exemple?

                    K A 3 Replies Last reply
                    0
                    • N Nico1564

                      Ok so to do that, i should modify this part of the QtGuiApplication.cpp ?

                      	QString fichier = QFileDialog::getOpenFileName(this, "Ouvrir un fichier", QString(), "Images (*.png *.gif *.jpg *.jpeg)");
                      	if (fichier.isEmpty())
                      	{
                      		QMessageBox::critical(this, "Erreur", "Erreur dans la selection de l'image");
                      	}
                      	else
                      	{
                      		QMessageBox::information(this, "Fichier", "Vous avez selectionne :\n" + fichier);
                      		//create painter with fichier then draw my circle on this painter
                      		imgWidget->setImage(QImage(fichier));
                      		ui.horizontalLayout->addWidget(imgWidget);
                      		defCoos();
                      	}
                      

                      Another question on my circle, once I have drawn it, I could not delete it right ? Or there is a system of layer with QPainter or QImage like we should find in Photoshop for exemple?

                      K Offline
                      K Offline
                      kenchan
                      wrote on last edited by kenchan
                      #11

                      @Nico1564
                      I just edited my last reply with some code to paint on an image. Use an image format which works best for your needs.
                      No, using a painter you can't delete only overwrite. That is the difference between a painter and a scene.
                      If you manage your own primitives you can repaint the image when you need to I suppose.
                      They are low level things you are supposed to add the high level stuff like a Photoshop app does :-)

                      1 Reply Last reply
                      0
                      • N Nico1564

                        Ok so to do that, i should modify this part of the QtGuiApplication.cpp ?

                        	QString fichier = QFileDialog::getOpenFileName(this, "Ouvrir un fichier", QString(), "Images (*.png *.gif *.jpg *.jpeg)");
                        	if (fichier.isEmpty())
                        	{
                        		QMessageBox::critical(this, "Erreur", "Erreur dans la selection de l'image");
                        	}
                        	else
                        	{
                        		QMessageBox::information(this, "Fichier", "Vous avez selectionne :\n" + fichier);
                        		//create painter with fichier then draw my circle on this painter
                        		imgWidget->setImage(QImage(fichier));
                        		ui.horizontalLayout->addWidget(imgWidget);
                        		defCoos();
                        	}
                        

                        Another question on my circle, once I have drawn it, I could not delete it right ? Or there is a system of layer with QPainter or QImage like we should find in Photoshop for exemple?

                        K Offline
                        K Offline
                        kenchan
                        wrote on last edited by
                        #12

                        @Nico1564
                        I just built that sample you used. If you draw something with the painter in the drawOnImage() function you will see it drawn on top of the image.

                        N 1 Reply Last reply
                        0
                        • K kenchan

                          @Nico1564
                          I just built that sample you used. If you draw something with the painter in the drawOnImage() function you will see it drawn on top of the image.

                          N Offline
                          N Offline
                          Nico1564
                          wrote on last edited by Nico1564
                          #13

                          @kenchan yes i just test it but it overwrite the first image (wich is a map, let's call it like this if you agree), so i have to set the backgroud of the draw to transparent
                          EDIT : even setting the background transparent, the map disappear

                          K 1 Reply Last reply
                          0
                          • N Nico1564

                            @kenchan yes i just test it but it overwrite the first image (wich is a map, let's call it like this if you agree), so i have to set the backgroud of the draw to transparent
                            EDIT : even setting the background transparent, the map disappear

                            K Offline
                            K Offline
                            kenchan
                            wrote on last edited by kenchan
                            #14

                            @Nico1564
                            Hm, well i just made the sample load the Qt image in the constructor. Then drew a rectangle with the painter in the drawOnImage() functions. That function gets called from the drawForeground() function so it gets refreshed all the time.
                            You draw another image but that should get over written by what ever is drawn in the drawOnImage(). Now, I am not sure when you are calling the setBackgroundBrush() function but I would suggest you only call that before you do any other drawing and not after, just to be on the safe side.

                            1 Reply Last reply
                            1
                            • N Nico1564

                              Ok so to do that, i should modify this part of the QtGuiApplication.cpp ?

                              	QString fichier = QFileDialog::getOpenFileName(this, "Ouvrir un fichier", QString(), "Images (*.png *.gif *.jpg *.jpeg)");
                              	if (fichier.isEmpty())
                              	{
                              		QMessageBox::critical(this, "Erreur", "Erreur dans la selection de l'image");
                              	}
                              	else
                              	{
                              		QMessageBox::information(this, "Fichier", "Vous avez selectionne :\n" + fichier);
                              		//create painter with fichier then draw my circle on this painter
                              		imgWidget->setImage(QImage(fichier));
                              		ui.horizontalLayout->addWidget(imgWidget);
                              		defCoos();
                              	}
                              

                              Another question on my circle, once I have drawn it, I could not delete it right ? Or there is a system of layer with QPainter or QImage like we should find in Photoshop for exemple?

                              A Offline
                              A Offline
                              Asperamanca
                              wrote on last edited by Asperamanca
                              #15

                              @Nico1564 said in How to draw on Image loaded in a QGraphicsView:

                              Ok so to do that, i should modify this part of the QtGuiApplication.cpp ?

                              	QString fichier = QFileDialog::getOpenFileName(this, "Ouvrir un fichier", QString(), "Images (*.png *.gif *.jpg *.jpeg)");
                              	if (fichier.isEmpty())
                              	{
                              		QMessageBox::critical(this, "Erreur", "Erreur dans la selection de l'image");
                              	}
                              	else
                              	{
                              		QMessageBox::information(this, "Fichier", "Vous avez selectionne :\n" + fichier);
                              		//create painter with fichier then draw my circle on this painter
                              		imgWidget->setImage(QImage(fichier));
                              		ui.horizontalLayout->addWidget(imgWidget);
                              		defCoos();
                              	}
                              

                              Another question on my circle, once I have drawn it, I could not delete it right ? Or there is a system of layer with QPainter or QImage like we should find in Photoshop for exemple?

                              If you want to work with something like layers, then you should not modify the image. GraphicsView is a framework that allows you to create multiple visual objects (images, circles, rectangles, texts,...) and manipulate them individually. You can move objects along x/y axis, you can define a z-order (which object is drawn on top, which below, etc.), and you can define transformations (scaling, rotating,...). You can group objects to they can be manipulated together. A bit like Powerpoint, really, but with code.

                              For what you want, it would make sense to create the image, and then a separate circle (QGraphicsEllipseItem) on top of it. Want to delete the circle later on? Just delete the QGraphicsEllipseItem, and your image stays.

                              I recommend reading about the basics of the QGraphicsView framework: https://doc.qt.io/qt-5/graphicsview.html

                              1 Reply Last reply
                              0
                              • N Offline
                                N Offline
                                Nico1564
                                wrote on last edited by
                                #16

                                Ok I have understand (i think) so I just try something in a new project (to see if i have really understood) but I failed and now I'm depressed .... :(

                                here is my new code :

                                testGraphicView.cpp

                                #include "testGraphicView.h"
                                
                                testGraphicView::testGraphicView(QWidget *parent)
                                	: QMainWindow(parent)
                                {
                                	ui.setupUi(this);
                                	scene = new QGraphicsScene(this);
                                	ui.graphicsView->setScene(scene);
                                	connect(ui.pushButton, SIGNAL(triggered), this, SLOT(Circle()));
                                }
                                
                                void testGraphicView::Circle()
                                {
                                	ellipse = scene->addEllipse(10, 10, 100, 100);
                                
                                }
                                

                                testGraphicView.h

                                #pragma once
                                
                                #include <QtWidgets/QMainWindow>
                                #include "ui_testGraphicView.h"
                                #include <QGraphicsView>
                                
                                
                                class testGraphicView : public QMainWindow
                                {
                                	Q_OBJECT
                                
                                public:
                                	testGraphicView(QWidget *parent = Q_NULLPTR);
                                
                                public slots :
                                	void Circle();
                                
                                private:
                                	Ui::testGraphicViewClass ui;
                                	QGraphicsScene *scene;
                                	QGraphicsEllipseItem *ellipse;
                                
                                };
                                
                                K 1 Reply Last reply
                                0
                                • N Nico1564

                                  Ok I have understand (i think) so I just try something in a new project (to see if i have really understood) but I failed and now I'm depressed .... :(

                                  here is my new code :

                                  testGraphicView.cpp

                                  #include "testGraphicView.h"
                                  
                                  testGraphicView::testGraphicView(QWidget *parent)
                                  	: QMainWindow(parent)
                                  {
                                  	ui.setupUi(this);
                                  	scene = new QGraphicsScene(this);
                                  	ui.graphicsView->setScene(scene);
                                  	connect(ui.pushButton, SIGNAL(triggered), this, SLOT(Circle()));
                                  }
                                  
                                  void testGraphicView::Circle()
                                  {
                                  	ellipse = scene->addEllipse(10, 10, 100, 100);
                                  
                                  }
                                  

                                  testGraphicView.h

                                  #pragma once
                                  
                                  #include <QtWidgets/QMainWindow>
                                  #include "ui_testGraphicView.h"
                                  #include <QGraphicsView>
                                  
                                  
                                  class testGraphicView : public QMainWindow
                                  {
                                  	Q_OBJECT
                                  
                                  public:
                                  	testGraphicView(QWidget *parent = Q_NULLPTR);
                                  
                                  public slots :
                                  	void Circle();
                                  
                                  private:
                                  	Ui::testGraphicViewClass ui;
                                  	QGraphicsScene *scene;
                                  	QGraphicsEllipseItem *ellipse;
                                  
                                  };
                                  
                                  K Offline
                                  K Offline
                                  kenchan
                                  wrote on last edited by
                                  #17

                                  @Nico1564 No no, That is not going to work. A QMainWindow is not going to work because it is not a QGraphicsView.
                                  You must but your QGraphicsView in the central widget of the main window, like the sample you used did.
                                  The sample is not a bad start but you should simplify it by just removing the functions you don't need for now.

                                  K 1 Reply Last reply
                                  0
                                  • K kenchan

                                    @Nico1564 No no, That is not going to work. A QMainWindow is not going to work because it is not a QGraphicsView.
                                    You must but your QGraphicsView in the central widget of the main window, like the sample you used did.
                                    The sample is not a bad start but you should simplify it by just removing the functions you don't need for now.

                                    K Offline
                                    K Offline
                                    kenchan
                                    wrote on last edited by kenchan
                                    #18

                                    @Nico1564
                                    I would suggest you don't call the drawOnImage(painter,imageSize); function.
                                    Don't add the initial image, just the one you want to add the way you want to add it.
                                    Add a function to your rOg_image to add the circle or whatever you want to draw on your image, or just draw it directly with the scene functions. Draw it after you have loaded your image.
                                    Call the draw function you made after you load and draw the image.
                                    Then you should see what ever you draw on top of the image and you will be able to zoom and scroll after you have zoomed in on the scene.
                                    Please do as @Asperamanca suggested and read up on the docs for the QGraphicsView and QGraphicsScene.

                                    1 Reply Last reply
                                    0
                                    • A Offline
                                      A Offline
                                      Asperamanca
                                      wrote on last edited by
                                      #19

                                      Here's a minimal GraphicsView sample, that draws an Ellipse:

                                      mainwindow.h

                                      #ifndef MAINWINDOW_H
                                      #define MAINWINDOW_H
                                      
                                      #include <QWidget>
                                      #include <QGraphicsView>
                                      #include <QGraphicsScene>
                                      
                                      class MainWindow : public QWidget
                                      {
                                          Q_OBJECT
                                      
                                      public:
                                          MainWindow(QWidget *parent = 0);
                                          ~MainWindow();
                                      
                                      private:
                                          QGraphicsScene* m_pScene;
                                          QGraphicsView* m_pView;
                                      };
                                      
                                      #endif // MAINWINDOW_H
                                      

                                      mainwindow.cpp

                                      #include "mainwindow.h"
                                      #include <QGraphicsEllipseItem>
                                      
                                      MainWindow::MainWindow(QWidget *parent)
                                          : QWidget(parent)
                                      {
                                          m_pScene = new QGraphicsScene(0,0,800,480,this);
                                      
                                          m_pView = new QGraphicsView(m_pScene, this);
                                          m_pView->setFrameStyle(QFrame::NoFrame);
                                          m_pView->setGeometry(0,0,800,480);
                                          m_pView->setAutoFillBackground(false);
                                          m_pView->show();
                                      
                                          // Add your image here, as a QGraphicsPixmapItem, and it will be drawn below the ellipse
                                          QGraphicsEllipseItem* testItem = new QGraphicsEllipseItem(20,30,120,70,0);
                                          m_pScene->addItem(testItem);
                                      }
                                      
                                      MainWindow::~MainWindow()
                                      {
                                      }
                                      

                                      main.cpp

                                      #include <QApplication>
                                      #include "mainwindow.h"
                                      
                                      int main(int argc, char *argv[])
                                      {
                                          QApplication a(argc, argv);
                                          MainWindow w;
                                          w.show();
                                      
                                          return a.exec();
                                      }
                                      

                                      Maybe you can go from there

                                      1 Reply Last reply
                                      0
                                      • N Offline
                                        N Offline
                                        Nico1564
                                        wrote on last edited by Nico1564
                                        #20

                                        Yeah i know that this work but i need to draw with fonctions. I successed to do that but I don't want to have the GraphicsView at the beginning of the program, and i want to add draws like an Ellipse (and the image) when i click on buttons.

                                        K A 2 Replies Last reply
                                        0
                                        • N Nico1564

                                          Yeah i know that this work but i need to draw with fonctions. I successed to do that but I don't want to have the GraphicsView at the beginning of the program, and i want to add draws like an Ellipse (and the image) when i click on buttons.

                                          K Offline
                                          K Offline
                                          kenchan
                                          wrote on last edited by kenchan
                                          #21

                                          @Nico1564
                                          Because you have a main window you can add menus, toolbars with buttons or dock widget with buttons. You can make these buttons and menus call your daw functions or what ever you want.
                                          The sample you used is a good basis to start from. the sample that @Asperamanca has posted is also a good basis to start from. Now it is up to you to study the docs for the gui elements and do what you need to do.

                                          1 Reply Last reply
                                          0

                                          • Login

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • Users
                                          • Groups
                                          • Search
                                          • Get Qt Extensions
                                          • Unsolved