setpixel of QGraphicsScene in Qt

2019-09-13 18:17发布

问题:

It's simple to draw line or ellipse just by using scene.addellipse(), etc.

QGraphicsScene scene(0,0,800,600);
QGraphicsView view(&scene);
scene.addText("Hello, world!");
QPen pen(Qt::green);
scene.addLine(0,0,200,200,pen);
scene.addEllipse(400,300,100,100,pen);
view.show();

now what should i do to set some pixel color? may i use a widget like qimage? by the way performance is an issue for me.thanks

回答1:

I think that performing pixel manipulation on a QImage would slow down your application quite a lot. A good alternative is to subclasse QGraphicsItem in a new class, something like QGraphicsPixelItem, and implement the paint function like this:

// code untested

void QGraphicsPixelItem::paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = 0)
{
    painter->save();

    foreach(const QPoint& p, pointList) {            
        // set your pen color etc.
        painter->drawPoint(p);
    }

    painter->restore();
}

where pointList is some kind of container that you use to store the position of the pixels you want to draw.