How do I write values ​​around a circle using the QPainter class without rotation?

The question is simple! I want something like this using a class QPainter

. enter image description here

I don't want the values ​​to be rotated. but using the method QPainter::rotate

I get values ​​like this (rotated format).

enter image description here

Can anyone help me draw a circle with values ​​like the first image using QPainter

+3


source to share


2 answers


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));
    }
}

      

+2


source


Draw text without formulas any way

ArcCubic
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));
    }

      

+2


source







All Articles