QT从入门到实战完整版 P36 P37

绘图事件

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();

    //绘图事件
    void paintEvent(QPaintEvent *);

private:
    Ui::Widget *ui;
};
#endif // WIDGET_H

widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include <QPainter>
#include <QBrush>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

}
//绘图事件
void Widget::paintEvent(QPaintEvent *)
{
    //实例化画家类 this指定的是绘图的设备
    QPainter painter(this);
    //设置画笔
    QPen pen(QColor(255,0,0));
    //设置画笔宽度
    pen.setWidth(3);
    //设置画笔风格
    pen.setStyle(Qt::DotLine);
    //让画家使用这个笔
    painter.setPen(pen);

    //设置画刷
    //QBrush brush(QColor(0,255,0));
    QBrush brush(Qt::green);
    //设置画刷风格
    brush.setStyle(Qt::Dense7Pattern);
    //让画家使用画刷
    painter.setBrush(brush);

    painter.drawLine(QPoint(0,0),QPoint(100,100)); //画线
    painter.drawEllipse(QPoint(100,100),50,50);//画圆(椭圆100 50)
    painter.drawRect(QRect(20,20,50,50)); //画矩形
    painter.drawText(QRect(10,200,150,50),"好好学习,天天向上");//画文字
}
Widget::~Widget()
{
    delete ui;
}

绘图高级设置

widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include <QPainter>
#include <QBrush>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

}
//绘图事件
void Widget::paintEvent(QPaintEvent *)
{
    /*

    //实例化画家类 this指定的是绘图的设备
    QPainter painter(this);
    //设置画笔
    QPen pen(QColor(255,0,0));
    //设置画笔宽度
    pen.setWidth(3);
    //设置画笔风格
    pen.setStyle(Qt::DotLine);
    //让画家使用这个笔
    painter.setPen(pen);

    //设置画刷
    //QBrush brush(QColor(0,255,0));
    QBrush brush(Qt::green);
    //设置画刷风格
    brush.setStyle(Qt::Dense7Pattern);
    //让画家使用画刷
    painter.setBrush(brush);

    painter.drawLine(QPoint(0,0),QPoint(100,100)); //画线
    painter.drawEllipse(QPoint(100,100),50,50);//画圆(椭圆100 50)
    painter.drawRect(QRect(20,20,50,50)); //画矩形
    painter.drawText(QRect(10,200,150,50),"好好学习,天天向上");//画文字
    */

    ////高级设置
    QPainter painter(this);
    /*
    //圆形
    painter.drawEllipse(QPoint(100,50),50,50);
    //设置 抗锯齿能力 效率较低
    painter.setRenderHint(QPainter::Antialiasing);
    painter.drawEllipse(QPoint(250,50),50,50);
    */
    //矩形
    painter.drawRect(QRect(20,20,50,50));
    painter.translate(100,0);//移动画家
    //保存画家状态
    painter.save();
    painter.drawRect(QRect(20,20,50,50));
    painter.translate(100,0);//移动画家
    painter.restore();//还原画家保存状态
    painter.drawRect(QRect(20,20,50,50));
}
Widget::~Widget()
{
    delete ui;
}
posted @ 2023-07-22 23:23  Vijurria  阅读(42)  评论(0编辑  收藏  举报