Qt绘制网格和曲线

绘制网格:

void Widget::drawGrid(QPainter &p, QRect &windRect)
{
    QRect   rect(windRect.left()+m_margins.left(),
                 windRect.top()+m_margins.top(),
                 windRect.width()-m_margins.left()-m_margins.right(),
                 windRect.height()-m_margins.top()-m_margins.bottom());

    if (!rect.isValid())
        return;

    QPen    penDot(Qt::DotLine);
    penDot.setColor(Qt::gray);

    QPen    penSolid(Qt::SolidLine);
    penSolid.setColor(Qt::black);
//    pen.setColor(this->palette().light().color());

    p.setPen(penSolid);
    p.drawRect(rect.adjusted(0,0,-1,-1));

    int     Xpos;
    qreal   Xvalue;
    QString xlab;
    QFontMetrics    textSize(this->font());
    QRect   textRect;
    for(int i=0;i<=m_XTicks;i++)
    {
        Xpos=rect.left()+i*m_xRatio; //
        Xvalue=m_xmin+i*m_xspan/m_XTicks;//
        p.setPen(penDot);
        p.drawLine(Xpos,rect.top(),Xpos,rect.bottom());
        p.setPen(penSolid);
        p.drawLine(Xpos,rect.bottom(),Xpos,rect.bottom()+5);

        xlab=QString::asprintf("%.1f",Xvalue);
        textRect=textSize.boundingRect(xlab);//得到字符串的rect

        p.drawText(Xpos-textRect.width()/2,
                   rect.bottom()+5+textRect.height(),
                   xlab);
    }

    xlab="time(sec)";
    textRect=textSize.boundingRect(xlab);//得到字符串的rect
    p.drawText(rect.left()+(rect.width()-textRect.width())/2,
               windRect.bottom()-textRect.height()/2,
               xlab);

    xlab="曲线绘图";
    textRect=textSize.boundingRect(xlab);//得到字符串的rect
    p.drawText(rect.left()+(rect.width()-textRect.width())/2,
               (m_margins.top()-textRect.height())/2+textRect.height(),
               xlab);

    int     Ypos;
    qreal   Yvalue;
    QString ylab;
    for(int i=0;i<=m_YTicks;i++)
    {
        Ypos=rect.bottom()-i*m_yRatio; //
        Yvalue=m_ymin+i*m_yspan/m_YTicks;//
        p.setPen(penDot);
        p.drawLine(rect.left(),Ypos,rect.right(),Ypos);
        p.setPen(penSolid);
        p.drawLine(rect.left()-5,Ypos,rect.left(),Ypos);

        ylab=QString::asprintf("%.1f",Yvalue);
        textRect=textSize.boundingRect(ylab);//得到字符串的rect

        p.drawText(rect.left()-10-textRect.width(),
                   Ypos+textRect.height()/2,
                   ylab);
    }

    ylab="函数值";
    textRect=textSize.boundingRect(ylab);//得到字符串的rect
    p.save();
    p.translate(0,windRect.height()/2); //平移到左侧中心
    p.rotate(-90);//逆时针旋转90度,变成正北为X轴,正东为Y轴

    p.drawText(-textRect.width()/2,
               (m_margins.left()-textRect.height())/2,
               ylab);
    p.restore();
}

绘制曲线:

void Widget::drawCurve(QPainter &p, QRect &windRect)
{

    QPolygon    curve(m_points.count());

    for(int i=0;i

你可能感兴趣的:(qt,开发语言)