PDA

View Full Version : Repainting widget



fear
25th March 2008, 18:40
My widget doesn't repaint correctly. I have no idea why.

Step 1:
http://img356.imageshack.us/img356/15/01ee2.th.jpg (http://img356.imageshack.us/my.php?image=01ee2.jpg)

Step 2:
http://img385.imageshack.us/img385/2371/02sa0.th.jpg (http://img385.imageshack.us/my.php?image=02sa0.jpg)

Step 3:
http://img385.imageshack.us/img385/3388/03hd1.th.jpg (http://img385.imageshack.us/my.php?image=03hd1.jpg)



[...]

class MainWindow : public QMainWindow
{
Q_OBJECT

public:
MainWindow();
MainWindow(QWidget * parent, const char * name);
~MainWindow();

public slots:
void clearFill();
void clear();
void reset();

protected:
void paintEvent(QPaintEvent * e);
void mouseMoveEvent(QMouseEvent * e);
void mousePressEvent(QMouseEvent * e);
void mouseDoubleClickEvent(QMouseEvent * e);

private:
Painter * painter;

[...]

void MainWindow::paintEvent(QPaintEvent * e)
{
painter->repaint();

QMainWindow::paintEvent(e);
}

[...]

class Painter
{
public:
[...]

private:
[...]
QPainter * painter;

[...]

void Painter::repaint()
{
for (int i = 0 ; i != width ; i++)
{
for (int j = 0 ; j != height ; j++)
drawPoint(array[i][j]);
}

for (SimpleSegmentList::iterator i = list.begin() ; i != list.end() ; i++)
drawLine((*i));
}

[...]

void Painter::drawPoint(const Point & p)
{
if (!painter)
return;

painter->setPen(QPen(QColor(0, 0, 0)));
painter->setBrush(QBrush(p.color()));
painter->drawEllipse(p.center().x(), p.center().y(), p.dia(), p.dia());
}

void Painter::drawLine(const SimpleSegment & s)
{
if (!painter)
return;

const int hdia = array[0][0].dia() / 2;

QPoint start = point(s.start()).center();
QPoint stop = point(s.stop()).center();

start.setX(start.x() + hdia);
start.setY(start.y() + hdia);
stop.setX(stop.x() + hdia);
stop.setY(stop.y() + hdia);

painter->setPen(QPen(s.color(), hdia));
painter->drawLine(start, stop);
}

[...]

Stukfruit
25th March 2008, 20:15
No idea, but here's a few brainfarts from when I read your sample code:

- Is your Painter a subclass from QPainter?
- Try to rename your repaint method to something else..

wysota
25th March 2008, 20:25
You have to create a new painter during each paint event and I don't see that in your code.

fear
26th March 2008, 08:37
Thank You. That's true. In fact api doc doesn't say it in explicit way. I was always using QPainter in this way:



Mostly, all this is done inside a paint event. (In fact, 99% of all QPainter use is in a reimplementation of QWidget::paintEvent(), and the painter is heavily optimized for such use.) Here's one very simple example:


void SimpleExampleWidget::paintEvent()
{
QPainter paint( this );
paint.setPen( Qt::blue );
paint.drawText( rect(), AlignCenter, "The Text" );
}



So now I realized that it MUST be used in such way.