Search code examples
c++qtqt5qpainter

Change circle colour every 5 seconds


I try to create a green circle which every 5 seconds disappears.

Actually, I have the green circle created with the QPainter method. I tried QTimer and others methods but I can't find the good solution.

I overrided the paintEvent function like this :

void MainWindow::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    Qt::BrushStyle style = Qt::SolidPattern;
    QBrush brush(Qt::green, style);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setBrush(brush);
    painter.drawEllipse(525, 5, 50, 50);
}
MainWindow::MainWindow() : QWidget()
{
    QTimer *ledtimer = new QTimer(this);
    connect(ledtimer, SIGNAL(timeout()), this, SLOT(run_led()));
    ledtimer->start(5000);
}

I tried to do something like this, but when i'm using run_led, it tells that painter is already removed (i tried in MainWindow class).

I understand the signal function and the timer, I used it in another files, so some tips would be appreciated. Am I supposed to use timers to make circles wink ?


Solution

  • Define a flag boolean that changes every 5 seconds and in paint use a brush as global variable

    void MainWindow::paintEvent(QPaintEvent *)
    {
        ....
        QBrush brush(myBrush, style);
        ...
    }
    
    and in slot (run_led)
    
    void MainWindow::run_led()
    {
        c != true;
        if(c)
        {
            myBrush=Qt::green;
        }
        else
        {
            myBrush=Qt::gray;
        }
    }