Qt QGraphicsScene中显示网格

QGraphicsLineItem

直接添加 QGraphicsLineItem 类型的item即可,在scene中拖动或者缩放时候,网格不会变形和模糊。

QPen pen2(QColor(128, 128, 128, 50));

    for (float x = 0.5 * MAP_SCALE; x <= GRID_RANGE * MAP_SCALE; x += 0.5 * MAP_SCALE)
    {
        QLineF line(x, 0, x, GRID_RANGE * MAP_SCALE);

        QGraphicsLineItem* tmpVertical = new QGraphicsLineItem(line);
        tmpVertical->setPen(pen2);

        gridItermVec.push_back(tmpVertical);

        if (show_grid_)
        {
            addItem(tmpVertical);
        }
    }

    //现在添加水平线
    for (float y = 0.5 * MAP_SCALE; y <= GRID_RANGE * MAP_SCALE; y += 0.5 * MAP_SCALE)
    {
        QLineF line(0, y, GRID_RANGE * MAP_SCALE, y);
        QGraphicsLineItem* tmpHorizontal = new QGraphicsLineItem(line);
        tmpHorizontal->setPen(pen2);
        gridItermVec.push_back(tmpHorizontal);

        if (show_grid_)
        {
            addItem(tmpHorizontal);
        }
    }

显示效果如下

QPixmap

1. QGraphicsScene继承类中的构造函数

2.重写 类的虚函数  void drawBackground(QPainter *painter, const QRectF &rect);

    QPolygonF myPolygon1;
    myPolygon1 << QPointF(0, 10) << QPointF(20, 10);
    QPolygonF myPolygon2;
    myPolygon2 << QPointF(10, 0) << QPointF(10, 20);
    QPixmap pixmap(20, 20);
    pixmap.fill(Qt::transparent);
    QPainter painter(&pixmap);

    QVector<qreal> dashes;//line style--虚线  
    qreal space = 2;
    dashes << 2 << space << 2 << space;
    QPen pen(Qt::lightGray, 1);
    pen.setDashPattern(dashes);
    pen.setWidth(1);

    painter.setPen(pen);
    painter.translate(0, 0);
    painter.drawPolyline(myPolygon1);
    painter.drawPolyline(myPolygon2);
    this->setBackgroundBrush(pixmap);*/

或者如下代码

    QPolygonF mypolygon1, mypolygon2;
    mypolygon1 << QPointF(0, 5) << QPointF(10, 5);
    mypolygon2 << QPointF(5, 0) << QPointF(5, 10);
    QPixmap pix(10, 10);
    pix.fill(Qt::transparent);
    QPainter painter(&pix);
    QVector <qreal> dashes;
    dashes << 2 << 2 << 2 << 2;
    QPen pen(Qt::darkCyan, 0.2);
    pen.setDashPattern(dashes);
    painter.setPen(pen);
    painter.translate(0, 0);
    painter.drawPolyline(mypolygon1);
    painter.drawPolyline(mypolygon2);
    this->setBackgroundBrush(pix);

二者没有本质区别都是用Qpixmap 作为背景实现的栅格,但是在 QGraphicsScene 中拖动鼠标时候会造成重影,目前不知道怎么消除

posted @ 2020-05-27 10:16  采男孩的小蘑菇  阅读(3274)  评论(2编辑  收藏  举报