Circlewidget. h
# Ifndef circlawidget_h # define circlawidget_h # include <qframe> # include <qvector> # include <qmouseevent> class circlewidget: Public qframe {q_objectpublic: circlewidget (qwidget * parent );~ Circlewidget (); Private: void paintevent (qpaintevent * event); Public: void adjust (INT period, int grain, int radius); qpoint origin (); // qpoint tocoord (qpoint P); // convert the point (x, y) of the GUI window to the point qpoint fromcoord (qpoint P) in the coordinate system ); // convert (x, y) in the coordinate system to the coordinates of the 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 = 20; // cycle m_grain = 1; // granularity m_radius = 10; // amplitude} circlewidget ::~ Circlewidget () {} void circlewidget: paintevent (qpaintevent * event) {qpainter painter (this); int width = This-> width (); int Height = This-> height (); qrect rect (, width, height); // set the background to black painter. setbrush (qbrush (qcolor (0x00,0x00, 0x00); painter. drawrect (rect); painter. setpen (qpen (qcolor (0,255, 0); // set the line to green qpoint o = Origin (); painter. drawline (qpoint (0, O. Y (), qpoint (width, O. Y (); // X axis painter. drawline (qpoint (O. X (), 0), qpoint (O. X (), height); // y axis // sine curve: Stretch qpoint p1 (0, 0) to the left and right from the coordinate origin; For (INT x = 0; x <width/2; x + = m_grain) {// y = sin (x) double angle = (double) x/m_period * 2*3.1415926; double Y = m_radius * sin (angle); qpoint P2 (x, y); // The right painter. drawline (fromcoord (P1), fromcoord (P2); // left 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 (); // update repainting} qpoint circlewidget: origin () {qrect r = This-> rect (); return r. center ();} // convert the point (x, y) of the GUI window to the point qpoint circlewidget in the mathematical Coordinate System: tocoord (qpoint P) {// center qpoint o = This-> origin (); qpoint result = P-O; result. sety (0-result. Y (); // return result of Y coordinate inversion;} // convert the (x, y) in the mathematical coordinate system into the GUI coordinate qpoint circlewidget: fromcoord (qpoint P) {// center qpoint o = This-> origin (); p. sety (0-P. Y (); // returns P + O in reverse return of Y coordinate ;}
Result:
Draw a sine curve in the QT custom window