PDA

View Full Version : QPainter and Qt analog clock example



Diph
25th September 2009, 15:56
Hi.

I used this example as a template: http://doc.trolltech.com/4.5/widgets-analogclock.html

What is the correct way to repaint clock if I want to repaint hand when button is pressed? If I use paintEvent() function to initialize clock and other function to repaint hand it doesn't work because painter is not active when button is pressed.

Should I even reimplement paintEvent() function?

I tried something like this but how do I paint this to the widget?


void Clock::init()
{
static const QPoint hand[3] = {
QPoint(7, 8),
QPoint(-7, 8),
QPoint(0, -90)
};

QColor handColor(204, 0, 0);
QColor lineColor(0, 0, 0);

int side = qMin(width(), height());

QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
painter.translate(width() / 2, height() / 2);
painter.scale(side / 200.0, side / 200.0);
painter.setPen(Qt::NoPen);
painter.setBrush(handColor);
painter.save();


painter.rotate(0.0);
painter.drawConvexPolygon(hand, 3);
painter.restore();

painter.setPen(lineColor);
for (int i=0; i < 12; ++i) {
painter.drawLine(88, 0, 96, 0);
painter.rotate(30.0);
}
}

void Clock::btnPressed(qreal angle)
{
static const QPoint hand[3] = {
QPoint(7, 8),
QPoint(-7, 8),
QPoint(0, -40)
};

QColor handColor(204, 0 ,0);

int side = qMin(width(), height());

QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
painter.translate(width() / 2, height() / 2);
painter.scale(side / 200.0, side / 200.0);
painter.setPen(Qt::NoPen);
painter.setBrush(handColor);
painter.save();

painter.rotate(angle);
painter.drawConvexPolygon(hand, 3);
painter.restore();
}

dbzhang800
25th September 2009, 16:34
from QPainter Class Reference

Warning: When the paintdevice is a widget, QPainter can only be used inside a paintEvent() function or in a function called by paintEvent(); that is unless the Qt::WA_PaintOutsidePaintEvent widget attribute is set. On Mac OS X and Windows, you can only paint in a paintEvent() function regardless of this attribute's setting.

Diph
25th September 2009, 18:34
So I just have to call paintEvent and update the variables like angle elsewhere?