其他分享
首页 > 其他分享> > QGraphicsScene绘制网格背景方法汇总

QGraphicsScene绘制网格背景方法汇总

作者:互联网

原文:https://wangjichuan.blog.csdn.net/article/details/120082214
一、通过设置背景画刷-QPixmap的方法

void ProjectScene::setGrid()
{
    if(showGrid) {
        //两条轴线
        QPolygonF myPolygon1;
        myPolygon1 << QPointF(0, 0) << QPointF(0, 128);
        QPolygonF myPolygon2;
        myPolygon2 << QPointF(0, 0) << QPointF(128, 0);

        //图像大小
        QPixmap pixmap(128, 128);
        pixmap.fill(Qt::transparent);
        QPainter painter(&pixmap);

        //虚线格式
        QVector<qreal> dashes;
        qreal space = 2;
        dashes << 2 << space << 2 << space;

        QPen pen1(Qt::lightGray, 2);
        pen1.setDashPattern(dashes);
        pen1.setWidth(2);
        painter.setPen(pen1);
        painter.translate(0, 0);
        painter.drawPolyline(myPolygon1);
        painter.drawPolyline(myPolygon2);

        painter.setPen(QPen(Qt::red, 4));
        painter.drawPoint(0,0);

        this->setBackgroundBrush(pixmap);
    }else {
        //图像大小
        QPixmap pixmap(128, 128);
        pixmap.fill(Qt::transparent);
        QPainter painter(&pixmap);

        this->setBackgroundBrush(pixmap);
    }
}

缺点:放缩视图,背景网格线会变的不均匀,例如:
在这里插入图片描述
这样在用户看来可能是很不美观的,目前不知道怎么调整。

二、重写void drawBackground(QPainter *painter, const QRectF &rect)

void ProjectScene::drawBackground(QPainter *painter, const QRectF &rect)
{
    if(!isShowGrid)
        return;

    Q_UNUSED(rect);
    QPen pen;

    qreal left=rect.left();
    qreal right=rect.right();
    qreal top=rect.top();
    qreal bottom=rect.bottom();

    //边界值调整
    left = (left/128)*128;
    right = (right/128)*128;
    top = (top/128)*128;
    bottom = (bottom/128)*128;

//    pen.setColor(QColor(0,0,0));
//    pen.setWidth(2);
//    pen.setStyle(Qt::SolidLine);
//    painter->setPen(pen);
//    //绘制坐标轴
//    painter->drawLine(left,0,right,0);
//    painter->drawLine(0,top,0,bottom);

    pen.setColor(QColor(60,60,60));
    pen.setWidth(0);
    pen.setStyle(Qt::DashLine);
    painter->setPen(pen);
    //绘制横线
    //绘制Y轴正半轴
    for(int i=0;i>=top;i-=128)
    {
        painter->drawLine(left,i,right,i);
    }
    //绘制Y轴负半轴
    for(int i=0;i<=bottom;i+=128)
    {
        painter->drawLine(left,i,right,i);
    }

    //绘制竖线
    //绘制X轴正半轴
    for(int i=0;i<=right;i+=128)
    {
        painter->drawLine(i,top,i,bottom);
    }
    //绘制X轴负半轴
    for(int i=0;i>=left;i-=128)
    {
        painter->drawLine(i,top,i,bottom);
    }
}

PS:此方法视图放缩,不会像使用背景画刷那样变得不均匀;

标签:right,QGraphicsScene,top,汇总,网格,pen,128,painter,left
来源: https://www.cnblogs.com/xiaohai123/p/16386649.html