Search code examples
c++qpainter

How to display dynamic circle using QPainter in Qt Creator


I can not display a dynamic circle in order to make it progressively grow with its center (indicated by the red cross) as its point of origin. It will seem that starting from the second circle, the point of origin moves and thus the circle does not enlarge anymore from its center. However, if the second circle becomes larger than the previous one, it will grow again from its center (as I want) The update or clear methods did not solve my problem, do you have any idea?

MainWindow.cpp :

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->graphicsView->setScene(&_scene);
    _cercle = new Cercle(0,0,1,1);
    _scene.addItem(&*_cercle);
    connect(&_animationTimer,SIGNAL(timeout()),this,SLOT(progressAnimation()));
    _animationTimer.setInterval(1);
    _animationTimer.start();
    tps = 1;
    a = 0;
}

MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::progressAnimation()
{
    tps++;
    a= a+0.2;
    if(tps%1000==0)
    {
       a=0;
      _cercle = new Cercle(0,0,1,1);
      _scene.addItem(&*_cercle);

    }
    _cercle->advance(a);

}

Cercle.cpp :

Cercle::Cercle(double x=0, double y=0,double size =0, double size2 = 0)
{
    _geometry = QRectF(x,y,size,size2);
}
QRectF Cercle::boundingRect()const
{
    return _geometry;
}
void Cercle::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    painter->setPen(Qt::white);
    painter->drawEllipse(_geometry);
}
void Cercle::advance(double a)
{
    _geometry = QRectF(0-a,0-a,0+a,0+a);
    this->setPos(0+a,0+a);
    this->boundingRect();
}

Screenshots :

1st centered circle

1st centered circle

2nd not centered circle

2nd not centered circle


Solution

  • Maybe your Cercle::advance method should be something like:

    void Cercle::advance(double a)
    {
        _geometry.adjust(-a, -a, a, a);
    }
    

    (no reason to adjust position again, and no reason to call boundingRect).

    See related dcoumentation for QRectF::adjust.