调用QPainter的接口来绘制一些基本的图形

头文件:

 #include <QMainWindow>
#include <QPainter> namespace Ui {
class MainWindow;
} class MainWindow : public QMainWindow
{
Q_OBJECT public:
explicit MainWindow(QWidget *parent = );
~MainWindow(); private:
void paintEvent(QPaintEvent *event); private:
Ui::MainWindow *ui;
int m_type;
};

源文件:

 #include <QRegExp>
#include <QPixmap>
#include "mainwindow.h"
#include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
m_type()
{
ui->setupUi(this);
} MainWindow::~MainWindow()
{
delete ui;
} void MainWindow::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event)
QPainter painter(this); if(m_type == ) // 绘制文本
{
painter.setPen(Qt::blue);
QFont font;
font.setFamily("Microsoft YaHei");
font.setPointSize();
font.setItalic(true);
font.setBold(true);
painter.setFont(font);
painter.drawText(rect(), Qt::AlignCenter, QString::fromLocal8Bit("Qt"));
}
else if(m_type == ) // 绘制直线
{
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setPen(Qt::blue);
painter.drawLine(QPointF(, height()), QPointF(width() / , height() / ));
}
else if(m_type == ) // 绘制矩形
{
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setPen(QPen(Qt::blue, ));
painter.setBrush(Qt::green);
painter.drawRect(, , , );
}
else if(m_type == ) // 绘制弧线
{
QRectF rect(90.0, 90.0, 80.0, 90.0);
int startAngle = * ;
int spanAngle = * ;
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setPen(QPen(Qt::blue, ));
painter.drawArc(rect, startAngle, spanAngle); }
else if(m_type == ) // 绘制椭圆,绘制圆
{
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setPen(QPen(Qt::blue, ));
painter.drawEllipse(QPointF(, ), , );
painter.setBrush(Qt::green);
painter.drawEllipse(QPointF(, ), , );
}
else if(m_type == ) // 绘制多边形
{
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setPen(Qt::blue);
static const QPointF points[] = {QPointF(, ), QPointF(, ), QPointF(, ), QPointF(, ), QPointF(, ), QPointF(, )};
painter.drawPolygon(points, );
}
else if(m_type == ) // 绘制图片
{
painter.setRenderHint(QPainter::Antialiasing, true);
painter.drawPixmap(rect(), QPixmap(":/images/pic.png"));
}
else if(m_type == ) // 绘制圆角矩形
{
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setPen(QPen(Qt::blue,,Qt::SolidLine));
painter.drawRoundRect(,,,,,);
}
else if(m_type == ) // 绘制扇形
{
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setPen(QPen(Qt::green,,Qt::SolidLine));
painter.drawPie(,,,,,);
}
else if(m_type == ) // 绘制弦
{
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setPen(QPen(Qt::green,,Qt::SolidLine));
painter.drawChord(,,,,,);
}
}
05-12 05:05