如图,想在界面上画个弧线和直线,于是继承QWidget得到类MainContainer,并实现了paintEvent函数。然后用类MainContainer定义centralWidget。
MainContainer.h
#pragma once #include "qwidget.h" #include <QPainter> class MainContainer : public QWidget{ Q_OBJECT public: MainContainer(QWidget *parent = 0) :QWidget(parent){}; ~MainContainer(); void addGeometry(int type,QRectF rect){ if (type == 0) arcList.push_back(rect); else if (type == 1) rectList.push_back(rect); } private: QPainter *painter; std::vector<QRectF> rectList; std::vector<QRectF> arcList; void paintEvent(QPaintEvent*){ painter = new QPainter; painter->begin(this); painter->setPen(QPen(Qt::green,2,Qt::DashLine)); //painter->setBrush(QBrush(Qt::red,Qt::SolidPattern)); for (auto rect : arcList){ painter->drawArc(rect, 30*16, 120*16); } for (auto rect : rectList){ painter->drawRoundRect(rect); } painter->end(); }; };
MainContainer.cpp
#include "MainContainer.h" MainContainer::~MainContainer() { }