如何使用QPainter类在圆周围编写文本?

6
问题很简单!我想要像这样的东西。可以使用QPainter类或使用Qt图形框架

enter image description here

1个回答

8

有几种方法可以使用指定的QPainterPath来实现这一点,具体请参见此处

以下是该页面上的第二个示例:

#include <QtGui>
#include <cmath>

class Widget : public QWidget
{
public:
    Widget ()
        : QWidget() { }
private:
    void paintEvent ( QPaintEvent *)
    {
        QString hw("hello world");
        int drawWidth = width() / 100;
        QPainter painter(this);
        QPen pen = painter.pen();
        pen.setWidth(drawWidth);
        pen.setColor(Qt::darkGreen);
        painter.setPen(pen);

        QPainterPath path(QPointF(0.0, 0.0));

        QPointF c1(width()*0.2,height()*0.8);
        QPointF c2(width()*0.8,height()*0.2);

        path.cubicTo(c1,c2,QPointF(width(),height()));

        //draw the bezier curve
        painter.drawPath(path);

        //Make the painter ready to draw chars
        QFont font = painter.font();
        font.setPixelSize(drawWidth*2);
        painter.setFont(font);
        pen.setColor(Qt::red);
        painter.setPen(pen);

        qreal percentIncrease = (qreal) 1/(hw.size()+1);
        qreal percent = 0;

        for ( int i = 0; i < hw.size(); i++ ) {
            percent += percentIncrease;

            QPointF point = path.pointAtPercent(percent);
            qreal angle = path.angleAtPercent(percent);   // Clockwise is negative

            painter.save();
            // Move the virtual origin to the point on the curve
            painter.translate(point);
            // Rotate to match the angle of the curve
            // Clockwise is positive so we negate the angle from above
            painter.rotate(-angle);
            // Draw a line width above the origin to move the text above the line
            // and let Qt do the transformations
            painter.drawText(QPoint(0, -pen.width()),QString(hw[i]));
            painter.restore();
        }
    }

};

int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    Widget widget;
    widget.show();
    return app.exec();
}

这个解决方案很好而且简单,但它并不是通用的。它会以错误的顺序打印从右到左的文本(希伯来语),并且在混合英语和希伯来语的双向文本中完全失败。 - Karry
1
QML中的另一个答案:这里 - Rémi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接