circlewidget.h

#ifndef CIRCLAWIDGET_H
#define CIRCLAWIDGET_H
#include <QFrame>
#include<QVector>
#include<QMouseEvent> class CircleWidget:public QFrame
{
Q_OBJECT
public:
CircleWidget(QWidget *parent);
~CircleWidget();
private:
void paintEvent(QPaintEvent *event); public:
void Adjust(int period, int grain, int radius);
QPoint origin(); // 坐标原点位置
QPoint toCoord(QPoint p); // 将GUI窗口的点(x,y)转换成坐标系统里的点
QPoint fromCoord(QPoint p); // 将坐标系内的(x,y)转成GUI的坐标
private: int m_period, m_grain, m_radius; }; #endif // CIRCLAWIDGET_H

circlewidget.cpp

# include"circlewidget.h"
#include<QPainter>
#include<QDebug>
#include<math.h> CircleWidget::CircleWidget(QWidget *parent):QFrame(parent)
{
m_period = ; //周期
m_grain = ; //粒度
m_radius = ; // 振幅
}
CircleWidget::~CircleWidget()
{ }
void CircleWidget::paintEvent(QPaintEvent *event)
{
QPainter painter(this); int width = this->width();
int height = this->height();
QRect rect(,, width, height); // 设置背景为黑色
painter.setBrush(QBrush(QColor(0x00,0x00, 0x00)));
painter.drawRect(rect); painter.setPen(QPen(QColor(, , ))); // 设置线条为绿色 QPoint o = origin();
painter.drawLine(QPoint(, o.y()), QPoint(width, o.y())); // x轴
painter.drawLine(QPoint(o.x(), ), QPoint(o.x(), height));// y轴 // 正弦曲线: 从坐标原点,向左、向右伸展
QPoint p1(,);
for(int x=; x<width/; x+=m_grain)
{
// y=sin(x)
double angle = (double) x / m_period * * 3.1415926;
double y = m_radius * sin(angle);
QPoint p2(x, y); // 右侧
painter.drawLine(fromCoord(p1), fromCoord(p2)); // 左侧
QPoint base(,);
painter.drawLine(fromCoord(base-p1), fromCoord(base-p2)); p1 = p2;
} } void CircleWidget::Adjust(int period, int grain, int radius)
{
m_period = period;
m_grain = grain;
m_radius = radius;
update(); // 更新重绘
} QPoint CircleWidget::origin()
{
QRect r = this->rect();
return r.center();
}
// 将GUI窗口的点(x,y)转换成数学坐标系统里的点
QPoint CircleWidget::toCoord(QPoint p)
{
// 圆心
QPoint o = this->origin();
QPoint result = p - o;
result.setY( - result.y()); // y坐标反转
return result;
}
// 将数学坐标系内的(x,y)转成GUI的坐标
QPoint CircleWidget::fromCoord(QPoint p)
{
// 圆心
QPoint o = this->origin();
p.setY( - p.y()); // y坐标反转
return p + o; }

结果:

qt 自定义窗口绘制正弦曲线-LMLPHP

05-12 08:49