PDA

View Full Version : Paint a compass on a GUI



trallallero
31st March 2010, 10:17
I need to paint a compass with a 360° rotating rectangle on a GUI.
The compass is like the one in this image:

http://lh4.ggpht.com/_HH5byQu0gx4/S7MSIrpKCRI/AAAAAAAAAbU/tYJ257z2SAQ/s800/Compass.JPG

The only part that needs to be painted is the rectangle ...
Is there some quick way to do that or do I have to paint it by myself with a QGraphicsView object ?

Lykurg
31st March 2010, 10:24
Use a normal Widget and do all the stuff in its paint event. Draw background picture and then rotate the painter and draw the rect. You don't need graphics view for that!

trallallero
31st March 2010, 10:29
Ok thanks, but how can I rotate the painter ?

Lykurg
31st March 2010, 10:36
QPainter::rotate() or you use a more complex QPainter::setTransform().

trallallero
31st March 2010, 10:45
Uhm, it's not so clear ...
I have a GUI with a lot of objects like buttons that will not rotate, of course.
Inside this GUI I put a QFrame ? QWidget ? something that has a painter, I guess.
Then I draw the rect (how ?) and rotate the painter ...

I have experience with QGraphicsView but not with drawing in normal QWidgets.

Lykurg
31st March 2010, 10:52
It is basic subclassing!
class Compass : public QWidget
{
Compass(QWidget* parent = 0) : QWidget(parent) {}
protected:
void paintEvent(QPaintEvent* event)
{
Q_UNUSED(event);
QPainter p(this);
// do your paintings here
}
};

Then you also have to provide a proper size hint method.

trallallero
31st March 2010, 10:53
Maybe I've got it :)
I've found this example: http://cartan.cas.suffolk.edu/qtdocs/widgets-analogclock.html

trallallero
31st March 2010, 10:54
Yes, it's clear now.
Thanks a lot :)

trallallero
31st March 2010, 13:02
Everything works now, but I have a problem ...
I have a QLabel 160x160 as a widget where I draw an ellipse 160x160 and a rectangle 160x20 in the center.
So I do the following to rotate the rectangle:



QTransform transform;
transform.translate(80, 80);
transform.rotate(m_RotateAngle);
p.setTransform(transform);


but the rectangle moves around the center, it doesn't rotate.
Any suggestion ?

Lykurg
31st March 2010, 13:16
First you have to translate the painter! See here:
#include <QtGui>

class Compass : public QWidget
{
public:
Compass(QWidget* parent = 0) : QWidget(parent)
{
rect = QRect(0, 0, 100, 100);
}
QSize sizeHint() const
{
return rect.size();
}
protected:
void paintEvent(QPaintEvent* event)
{
Q_UNUSED(event);
QPainter p(this);
p.setRenderHint(QPainter::Antialiasing, true);
p.drawEllipse(rect);

p.save();
p.translate(rect.center());
p.rotate(15);
p.drawRect(QRect(-20, -10, 40, 20));
p.restore();
}
private:
QRect rect;
};

int main(int argc, char* argv[])
{
QApplication a(argc, argv);
Compass c;
c.show();
return a.exec();
}

trallallero
31st March 2010, 13:46
Ah ok, I had to change the rectangle coordinates.
That's perfect now, thanks again ;)