简体   繁体   中英

Qt : Create a Stack of image

I'm new at Qt and I'm trying to design a simple application that draw lines for now. I managed to draw lines using QImage and the MouseEvent (the line starts at the mouse click and ends at the mouse release).

Now I would like to create a "ghost" line that appear during the mouseMoveEvent only. I would like to do that using a Stack (which will allow me later to manage the undo-redo) of QImage . However, I can't manage to even construct the stack, the program crashes without any explanation

Here is my declaration in my header class

private:
    QImage image;
    QStack <QImage> *history

Here is my constructor

Painty::Painty() : image(1920,1080, QImage::Format_ARGB32)
{
    image.fill(Qt::white);
    history = new QStack <QImage>;
}

Here are my functions :

void Painty::mousePressEvent(QMouseEvent *event)
{
     f_point = event->pos();
}

 void Painty::mouseReleaseEvent(QMouseEvent *event)
 {
    l_point = event->pos();
    addLine();
    history->push(image);
 }

 void Painty::mouseMoveEvent(QMouseEvent *event)
 {
    l_point = event->pos();
    addLine();
 }


 void Painty::paintEvent(QPaintEvent *event)
 {
    QWidget::paintEvent(event);
    QPainter painter(this);
    painter.drawImage(0,0,image);
 }

void Painty::addLine() 
{
     image=history->top();
     QPainter paint(&image);
     paint.drawLine(f_point,l_point);
     paint.end();
     this->update();
}

I tried to debug as much as I could but all I could realize is that the line that is making the program crash is history = new QStack <QImage>; but I don't know what is wrong with it.

You need to either push the empty image to the stack at the end of the constructor, or swap the lines

addLine();
history->push(image);

in mouseReleaseEvent(...) .

Otherwise at the first call to addLine() history->top() will be invalid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM