Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Clickable Drawn Object



  • Good day all,

    I am a beginner programmer student for C++ and Qt and I am getting close to the project deadline. I don't have much time to research and learn the answers so I would appreciate the simplest answer (some sample code would be nice).

    I am using an am437x board with Qt4.6 Yocto tools.
    My app requires a drawn circle (using Qpainter 'drawEllipse') to be clickable to display information into a Qlabel. What would be the best method to make this circle clickable?

    My sample code is as follows:

    mainheader.h

    #pragma once
    
    #include <QWidget>
    #include <QPainter>
    #include <QApplication>
    #include <QLabel>
    #include<Qt>
    
    class CGui : public QWidget {
    
      Q_OBJECT
    
      public:
        CGui(QWidget *parent = 0);
    
      private slots:
        void showInfo();
    
      private:
        Qlabel *lInfo;
    
      protected:
        void paintEvent(QPaintEvent *e);
        void drawCircle(QPainter *painter);
    }
    

    mainheader.cpp

    CGui::CGui(QWidget *parents)
        : QWidget(parent)  {
    
      lInfo = new Qlabel("Not Clicked",this);
      lInfo ->setGeometry(150, 15, 150, 50);
    
      /* Code for clicking circle maybe goes here invoking the showInfo() function*/ 
    }
    
    void CGui::paintEvent(QPaintEvent *e){
      Q_UNUSED(e);
    
      QPainter painter(this);
    
      drawCircle(&painter);
    }
    
    void CGui::drawCircle(QPainter *painter){
      painter->setPen(Qt::red);
      painter->setBrush(Qt::red);
    
      painter->drawEllipse(350, 190,100,100);
    }
    
    void CGui::showInfo(){
      lInfo->setText("Clicked");
    }
    

    main.cpp

    #include "mainheader.h"
    
    int main(int argc, char *argv[]) {
      QApplication app(argc,argv);
    
      CGui window;
      window.ShowFullScreen();
    
      return app.exec();
    }
    

    Please also not that the position of the circle may change upon every call for update(); therefore the position of the clickable are must vary with the position of the circle.
    Thank you everyone. Any help is appreciated.

    Kind regards,
    Shoaib


  • Lifetime Qt Champion

    @Shoaib-Muhammad You can override https://doc.qt.io/qt-5/qwidget.html#mousePressEvent and check the cursor position there to decide whether it is over your circle or not.



  • Thank you jsulm,

    I will reply here for further problems I encounter on the topic. I have never done this method before.

    Kind regards,
    Shoaib


Log in to reply