How do I write values around a circle using the QPainter class without rotation?
Here is the simplest code for how I would do it. Assuming I am drawing in the paint event of the widget:
#define PI 3.14159265
[..]
void Widget::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
QPoint center = rect().center();
painter.drawEllipse(center, 2, 2);
const int radius = 100;
// Draw semicircle with texts on every 30".
for (double i = .0; i <= 180.0; i += 30.0) {
QPoint p(center.x() + radius * cos(i * PI / 180.0),
center.y() - radius * sin(i * PI / 180.0));
painter.drawText(p, QString::number(i));
}
}
source to share
Draw text without formulas any way
Create Path
There is a class QPainterPath
with which you can draw any path using a bunch of methods.
In your case, you can use arcTo
.
QPainterPath path;
path.arcTo(rect, 210, -240.0);
Calculate the starting point
There is a little difficulty here: the path has a starting point. If you call arcTo
, it will create a line up to the start of the arc and then draw the arc. Therefore, you need to call moveTo
and pass the starting point of the arc as an argument. But where can you get it? Calculate with arc formula? Not. Of course, you can experiment and set an approximate point, or open a book and find the formula for any curve, but there is an easy way to find out the starting point: draw a curve of zero size and get its last point:
QPainterPath initialPath;
initialPath.arcTo(rect, 210, 0);
path.moveTo(initialPath.currentPosition());
Draw Text
Once you have this path, you can get any point on the path with pointAtPercent
and use drawText
to draw text there.
Here is the code to draw the arc and numbers below:
QPainter p(this);
p.drawArc(rect(), 210 * 16, -240 * 16);
QRectF rect(20, 20, width() - 40, height() - 40);
QPainterPath initialPath;
initialPath.arcTo(rect, 210, 0);
QPainterPath path;
path.moveTo(initialPath.currentPosition());
path.arcTo(rect, 210, -240.0);
for (int i = 0; i <= 10; i += 1)
{
p.drawText(path.pointAtPercent((qreal)i / 10), QString::number(i));
}
source to share