网站主页 优帮云/网站网络推广公司
一、效果图
二、工程构造思路
QPainter绘制单个文本,利用translate和rotate方法旋转单个文字到指定弧度。配合QPropertyAnimation即可实现环形文字效果。
三、代码片段
#ifndef ROUNDTXTWIDGET_H
#define ROUNDTXTWIDGET_H#include <QObject>
#include <QWidget>
#include <QPainter>
#include <QFontMetrics>
#include <QPropertyAnimation>
class RoundTxtWidget : public QWidget
{Q_OBJECT
public:RoundTxtWidget(QWidget *parent = nullptr);~RoundTxtWidget();void paintEvent(QPaintEvent *event);void startAnimation();
private slots:void valueChanged_slot(QVariant value);
private:int m_startAngle;int m_margin;QString m_text;
};#endif // ROUNDTXTWIDGET_H
#include "roundtxtwidget.h"
RoundTxtWidget::RoundTxtWidget(QWidget *parent)
{m_text = "abcdefghijklmnopqrstuvwxyz";m_margin = 20;m_startAngle = 0;startAnimation();
}RoundTxtWidget::~RoundTxtWidget()
{}
void RoundTxtWidget::paintEvent(QPaintEvent *event)
{QPainter painter(this);painter.translate(this->width()/2,this->height()/2);painter.rotate(m_startAngle);QFont font;font.setPixelSize(12);painter.setFont(font);painter.save();int textCount = m_text.count();double stepAngle = 360.0 / textCount;painter.setPen(QColor("blue"));QFontMetrics fontm(font);for (int i = 0; i < textCount; i++){int textWidth = fontm.width(m_text.at(i));int textHeight = fontm.height();int radius = qMin(this->width(), this->height()) / 2 - m_margin - textHeight / 2;QRect textRect(-textWidth / 2, -(radius + textHeight / 2), textWidth, textHeight + 1);painter.drawText(textRect, Qt::AlignCenter, m_text.at(i));painter.rotate(stepAngle);}painter.restore();
}
void RoundTxtWidget::startAnimation()
{QPropertyAnimation *pAnimation = new QPropertyAnimation(this, QByteArray());connect(pAnimation, SIGNAL(valueChanged(QVariant)), this, SLOT(valueChanged_slot(QVariant)));pAnimation->setStartValue(0);pAnimation->setEndValue(360);pAnimation->setDuration(6000);pAnimation->setLoopCount(-1);pAnimation->start();
}
void RoundTxtWidget::valueChanged_slot(QVariant value)
{m_startAngle = value.toInt();update();
}
四、结束语
欢迎各方多多指教
QQ:519096571
e-mail:519096571@qq.com