PDA

View Full Version : Help regarding QPainter issue on QMainWindow



ancest
25th March 2010, 13:04
Hai friends,
I am new to qt4 and i have a problem in using QPainter to draw lines when mouse is moving by reimplementing mouseMoveEvent.
Problem is that the old drawings are erased after paintEvent.
So only the last drawing is retained on screen after paintEvent. Is there any way to save the old drawings in Qt4 ? Please help?

code is as follows :-

void MainWindow:: paintEvent(QPaintEvent* event)
{
QPainter p;
p.begin(this);
p.drawLine(oldX, oldY, X, Y); // where oldX and oldY are older position of mouse before moving it and X and Y are new positions of mouse.
p.end();
}

void MainWindow::mouseMoveEvent(QMouseEvent* e)
{
oldX = X;
oldY = Y;
X=e->x();
Y=e-Y();
repaint(); // To repaint after mouseMoveEvent()
}

toutarrive
25th March 2010, 13:13
Put all the coordinates in a QVector<QLineF> and use QPainter::drawLines ( const QLineF * lines, int lineCount ) to draw all the lines.

Lykurg
25th March 2010, 13:43
Storing all points can be damn huge. The magic is window attribute Qt::WA_StaticContents! See the Scribble Example which comes with Qt.

toutarrive
25th March 2010, 14:22
How the magic works? Does it mean that the painting is cached somehow and that the paint event occurs only for new parts?

Lykurg
25th March 2010, 15:12
Hey, I was to fast by writing that reply. It's NoSystemBackground which is responsible that previous things are not cleaned. See this small example:
#include <QtGui>

class test : public QWidget
{
public:
test(QWidget *parent = 0) : QWidget(parent)
{
setAttribute(Qt::WA_NoSystemBackground, true);
setAttribute(Qt::WA_StaticContents, true);
first = true;
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(update()));
timer->start(500);
}
void paintEvent(QPaintEvent */*event*/)
{
QPainter painter(this);
if (first)
{
painter.setBrush(Qt::yellow);
painter.drawRect(this->rect());
first = false;
}
else
{
painter.setPen(Qt::red);
QPoint p(qrand() % this->width(), qrand() % this->height());
painter.drawRect(QRect(p.x(), p.y(), 10, 10));
}
}

bool first;
};



int main(int argc, char **argv)
{
QApplication app(argc, argv);
test t;
t.show();
return app.exec();
}


(Resizing is not working. For that you have to alter the paint method and react on the resize event.)

maly
13th November 2011, 08:09
This is great! Since I also got this kind of problem, the reply from Qt developer is very meaningful and it helps me alot either. thank :)

Lykurg
13th November 2011, 09:31
You are welcome! :)