效果
// 定义一个新的类
#ifndef PAINTERAREA_H #define PAINTERAREA_H #include <QObject> #include <QWidget> //QPen 画笔是基本的图形对象,绘制直线、曲线、多边形等形状 #include <QPen> //QBrush 画刷是基本的图形对象,主要用于填充,比如矩形、多边形等形状 #include <QBrush> #include <QPainter> class PainterArea : public QWidget { Q_OBJECT public: explicit PainterArea(QWidget *parent = nullptr); // 绘制直线、长方形 enum shape{Line,Rectangle}; void setshape(shape);//次函数实现绘制形状 void setPen(QPen); void setBrush(QBrush); void paintEvent(QPaintEvent *event); //重绘事件(本来就有的函数) void setFillrule(Qt::FillRule); //填充规则 signals: public slots: private: shape shp; //形状 QPen pen; //画笔 QBrush qbrush; //画刷 Qt::FillRule fillrle; //规则 public slots: }; #endif // PAINTERAREA_H
//实现定的的新的类
#include "painterarea.h" PainterArea::PainterArea(QWidget *parent) : QWidget(parent) { //调色板来改变背景颜色 setPalette(QPalette(Qt::blue)); // 用于当前窗口是否需要绘制背景 setAutoFillBackground(true); //设置最小尺寸 setMinimumSize(400,400); } void PainterArea::setshape(shape sh){ shp=sh; update(); } void PainterArea::setPen(QPen sh) { pen=sh; update(); } void PainterArea::setBrush(QBrush sh) { qbrush = sh; update(); } void PainterArea::paintEvent(QPaintEvent *event) { QPainter p(this); p.setPen(pen); p.setBrush(qbrush); QRect rect(55,110,290,180); switch (shp) { case Line://实现直线 p.drawLine(rect.topLeft(),rect.bottomRight()); break; case Rectangle: p.drawRect(rect); break; default: break; } } void PainterArea::setFillrule(Qt::FillRule rle) { fillrle=rle; update();//重新绘制区域窗体 }
#ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include "painterarea.h" #include <QLabel> #include <QGridLayout> #include <QComboBox> //颜色 #include <QColorDialog> class Widget : public QWidget { Q_OBJECT public: Widget(QWidget *parent = 0); ~Widget(); private: PainterArea *labelshapeArea; QLabel *labelshap; QComboBox *comboboxShape; QGridLayout *glayout; private slots: void dispShapeFunc(int); }; #endif // WIDGET_H
#include "widget.h" #include <QDebug> Widget::Widget(QWidget *parent) : QWidget(parent) { labelshapeArea=new PainterArea; glayout = new QGridLayout; //控制面板布局 setWindowTitle("QT绘图框架测试(QPainter)类"); labelshap = new QLabel("绘制形状"); comboboxShape = new QComboBox; comboboxShape->addItem("Line",PainterArea::Line); comboboxShape->addItem("Rectangle",PainterArea::Rectangle); glayout->addWidget(labelshap,0,0); glayout->addWidget(comboboxShape,0,1); QHBoxLayout *mainLayout= new QHBoxLayout(this); //整体布局 mainLayout->addWidget(labelshapeArea); //向布局 添加控件 mainLayout->addLayout(glayout); //向布局添加布局 connect(comboboxShape,SIGNAL(activated(int)),this,SLOT(dispShapeFunc(int))); } Widget::~Widget() { } void Widget::dispShapeFunc(int v) { PainterArea::shape sp=PainterArea::shape(comboboxShape->itemData(v,Qt::UserRole).toInt()); qDebug() << sp; labelshapeArea->setshape(sp); }
标签:Widget,14,PainterArea,void,QWidget,comboboxShape,include,绘制,QPainter From: https://www.cnblogs.com/baisedeyu/p/17893898.html