参考资料:https://blog.csdn.net/what951006/article/details/52876513

效果图:

 

代码:

void WgtText::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);

    QFont font;
    font.setFamily("Microsoft YaHei");
    // 大小
    font.setPointSize(20);
    // 斜体
    font.setItalic(true);
    // 设置字母大小写
    //font.setCapitalization(QFont::SmallCaps);
    // 设置字符间距
    font.setLetterSpacing(QFont::AbsoluteSpacing, 20);
    // 设置加粗
    //font.setBold(true);
    // 使用字体
    painter.setFont(font);

    QString m_Text1("AAAAAAAAAAAA");
    QString m_Text2("BBBBBBBBBBBB");
    QFontMetrics metrics = painter.fontMetrics();

    int y=((height()-20)/2-metrics.height())/2+20;
    int bottomwidth=width()-metrics.width(m_Text2);

    QLinearGradient m_normalGradient;

   /*
    *frist part
    */
       m_normalGradient.setStart(0, y);
       m_normalGradient.setFinalStop(0, y+metrics.height());
       m_normalGradient.setColorAt(0, QColor(255,0,0));
       m_normalGradient.setColorAt(1, QColor(255,255,0));


       painter.setPen(QPen(m_normalGradient,0));
       painter.drawText(10, y,metrics.width(m_Text1),metrics.height(),Qt::AlignLeft, m_Text1);

   /*
    *second part
   */
       m_normalGradient.setStart(0, y+height()/2);
       m_normalGradient.setFinalStop(0, y+(height()-20)/2+metrics.height());
       m_normalGradient.setColorAt(0, QColor(0,255,0));
       m_normalGradient.setColorAt(1, QColor(0,0,255));


       painter.setPen(QPen(m_normalGradient,0));
       painter.drawText(bottomwidth-10, y+(height()-20)/2,metrics.width(m_Text2),metrics.height(),Qt::AlignLeft, m_Text2);

}
posted on 2018-12-19 20:12  邶风  阅读(879)  评论(0编辑  收藏  举报