widget.h
void paintEvent(QPaintEvent* evt);widget.cpp
#include "Widget.h" #include <QPainter> Widget::Widget(QWidget *parent): QWidget(parent) { } void Widget::paintEvent(QPaintEvent* evt) { QPainter painter(this); painter.save(); painter.setPen(QPen(Qt::black)); painter.setFont(QFont("Arial", 15)); painter.rotate(0); painter.drawText(20, 30, "#include <stdio.h>"); painter.setPen(QPen(Qt::red)); painter.setFont(QFont("Courier New", 20)); painter.rotate(20); painter.drawText(30, 40, "#include <stdio.h>"); painter.restore(); painter.drawText(80, 90, "#include <stdio.h>"); } Widget::~Widget() { } 实例分析:(下面图像动态从小变到大) 解决方案分析 小技巧 坐标计算widgt.h
#ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include <QTimer> class Widget : public QWidget { Q_OBJECT int m_sizeFactor; QTimer m_timer; protected slots: void onTimeOut(); protected: void paintEvent(QPaintEvent* evt); public: Widget(QWidget *parent = 0); ~Widget(); }; #endif // WIDGET_Hwidgt.cpp
#include "Widget.h" #include <QPainter> #include <QFont> #include <QRect> #include <QFontMetrics> Widget::Widget(QWidget *parent): QWidget(parent) { m_sizeFactor = 0; m_timer.setParent(this); connect(&m_timer, SIGNAL(timeout()), this, SLOT(onTimeOut())); m_timer.start(100); } void Widget::onTimeOut() { update(); } void Widget::paintEvent(QPaintEvent* evt) { QPainter painter; const QString text = "D.T.SoftWare"; QFont font("Courier New", (5+m_sizeFactor++)%50); QFontMetrics metrics(font); const int w = metrics.width(text); const int h = metrics.height(); QRect rect((width()-w)/2, (height()-h)/2, w, h); painter.begin(this); painter.setPen(Qt::blue); painter.setFont(font); painter.drawText(rect, Qt::AlignCenter, text); painter.end(); } Widget::~Widget() { } 小结 1、QPainter 能够根据需要任意绘制文本 2、QPainter 可以自定义文本颜色,位置,字体等参数 3、QPainter 绘制文本时可以通过参数控制实现动画效果 4、QPainter 能够将文本绘制与图片(图片水印)